使用 Kotlin 和 XML 的 Android 按钮

在本教程中,我们将学习如何使用Kotlin编程在Android应用程序中创建按钮。

Android按钮概述

Android Button类扩展了TextView。按钮是一个UI小部件,用于从用户获取点击交互以触发应用程序中的操作。可以在XML布局中创建按钮,也可以在Android Studio项目中创建Kotlin活动类。

在XML布局中创建按钮

1<Button
2android:id="@+id/button"
3android:layout_width="wrap_content"
4android:layout_height="wrap_content"
5android:text="Androidly Button"/>
  • android:用于设置按钮上的唯一标识。
  • android:ext用于设置按钮内部的文本。默认情况下,文本以大写字母显示。
  • android:onClick用于定义点击按钮时在活动中调用的Kotlin函数。它是一个点击监听程序。
  • android:Backmark用于设置按钮上的背景颜色/可绘制。

提示 :要避免显示大写字母,请使用属性android:textAllCaps=false``

关于如何在XML布局中自定义按钮的更多详细信息,请参考Android按钮教程。

按钮点击监听器

我们也可以通过编程方式设置按钮监听器。以下是两个主要的听众:

1.setOnClickListener-点击按钮时触发。 2.setOnLongClickListner-按钮长按时触发。

下面的代码段在按钮上设置了setOnClickList。

1button.setOnClickListener(object : View.OnClickListener {
2            override fun onClick(v: View?) {
3                //your implementation goes here
4            }
5        })

上面的代码可以转换为lambda表达式以使其简短。

1button.setOnClickListener {   
2      textView.text = "Androidly Buttons"
3    }

同样,setOnLongClickListener可以按以下方式定义。

 1button.setOnLongClickListener {
 2        textView.text = "Androidly Button Long click"
 3        true
 4    }
 5
 6//or
 7button.setOnLongClickListener {
 8        textView.text = "Androidly Button Long click"
 9        false
10    }

在上面的代码中,每个表达式中的最后一个语句是return语句。

  • 如果setOnLongClickList返回true,则意味着不会触发setOnClickList。
  • 如果setOnLongClickList返回false,则意味着将触发setOnClickList。

这就是所谓的消费事件 。第一个案例使用该事件。

使用Kotlin的Android按钮

我们将开发一个应用程序,用于在单击按钮时递增TextView的计数器。我们将使用Kotlin来创建按钮。我们还将了解不同的按钮点击处理程序。

1.项目结构

创建一个新的Android Studio项目。确保在初始设置中启用Kotlin支持。完成后,下面是您应该看到的项目结构。安卓按钮项目structure

2.Kotlin按钮代码

ACTIVATION_MAIN.Layout文件类似以下代码。

 1<?xml version="1.0" encoding="utf-8"?>
 2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3    android:id="@+id/linearLayout"
 4    android:layout_width="match_parent"
 5    android:layout_height="match_parent"
 6    android:gravity="center"
 7    android:orientation="vertical">
 8
 9    <TextView
10        android:id="@+id/txtCounter"
11        android:layout_width="wrap_content"
12        android:layout_height="wrap_content"
13        android:text="@string/number_zero"
14        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
15        android:textColor="#000" />
16
17    <Button
18        android:id="@+id/btnIncrementByOne"
19        android:layout_width="wrap_content"
20        android:layout_height="wrap_content"
21        android:onClick="addOne"
22        android:text="@string/increment_by_one" />
23
24</LinearLayout>

我们已经使用了LinearLayout,它以线性方式(水平或垂直)保存视图。建议在字符串.xml文件中设置字符串,而不是对它们进行硬编码。为了获取字符串资源,我们使用@字符串/名称_of_字符串android按钮字符串xml函数addOne(view:view)在MainActivity.kt Kotlin类中定义。MainActivity.kt类的代码如下所示。

 1package net.androidly.androidlybuttons
 2
 3import android.support.v7.app.AppCompatActivity
 4import android.os.Bundle
 5import android.support.v4.content.ContextCompat
 6import android.view.View
 7import android.view.ViewGroup
 8import android.widget.Button
 9import android.widget.LinearLayout
10import kotlinx.android.synthetic.main.activity_main.*
11
12class MainActivity : AppCompatActivity(), View.OnClickListener {
13
14    override fun onCreate(savedInstanceState: Bundle?) {
15        super.onCreate(savedInstanceState)
16        setContentView(R.layout.activity_main)
17
18        var androidlyButton = Button(this)
19        androidlyButton.apply {
20            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
21            text = "Double the value"
22            setAllCaps(false)
23            textSize = 20f
24            id = R.id.btnDouble
25        }
26
27        androidlyButton.setOnClickListener(this)
28        linearLayout.addView(androidlyButton)
29
30        androidlyButton = Button(this)
31        androidlyButton.apply {
32            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
33            text = "RESET"
34            textSize = 20f
35            setTextColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimaryDark))
36            id = R.id.btnReset
37            setOnLongClickListener {
38                txtCounter.text = 0.toString()
39                true
40            }
41        }
42        androidlyButton.setOnClickListener(this)
43        linearLayout.addView(androidlyButton)
44
45    }
46
47    override fun onClick(v: View?) {
48        when (v?.id) {
49            R.id.btnDouble -> {
50                txtCounter.text = (txtCounter.text.toString().toInt() * 2).toString()
51            }
52            R.id.btnReset -> {
53                txtCounter.text = (-100).toString()
54            }
55            else -> {
56            }
57        }
58    }
59
60    fun addOne(view: View) {
61        txtCounter.text = (txtCounter.text.toString().toInt() + 1).toString()
62    }
63}

要点:

1.IMPORT kotlinx.android.synthetic.main.activity_main.* 语句自动从我们类的xml中获取视图ID。因此,我们不必再使用findViewByID。 2.点击btnIncrementByOne会触发Fun addOne(view:view)。函数声明中必须定义(view:view)参数。 3.以编程方式创建一个Button,并使用以下代码在父视图(此处为LinearLayout)中设置它。

1Var androidlyButton=Button(This)
2LinearLayout.addView(AndroidlyButton)

4.可以使用Apply{}lambda表达式,而不是在Button类上调用成员函数。 5.layoutParams用于定义按钮的宽度和高度。Match_PARENT将宽度/高度设置为等于线性布局。WRAP_CONTENT将视图包装到内容的大小。 6.可以在res|Values|ids.xml 下以编程方式设置id。安卓按钮ids 7.我们在MainActivity.kt类中定义了View.OnClickListener接口。因此,我们需要覆盖它的onClick()函数。 8.在onClick函数内部,我们使用了Kotlin When语句,相当于其他语言中的Switch。 9.要触发onClick函数,必须使用上下文(this)在按钮上注册setOnClickListener

输出:安卓按钮kotlin output

下载项目:AndroidlyButtons

Published At
Categories with 技术
Tagged with
comments powered by Disqus