Android RadioButton,使用Kotlin的RadioGroup

In this tutorial, we’ll be discussing and implementing RadioButton and RadioGroups in our Android Application using Kotlin.

在本教程中,我们将使用Kotlin在Android应用程序中讨论和实现RadioButton和RadioGroup。

Android单选按钮 (Android RadioButton)

A RadioButton is a widget which can be set to checked or an unchecked state. Once a RadioButton is checked you cannot uncheck it unless it’s present inside a RadioGroup.
A RadioGroup is a container that holds RadioButtons. At a time inside a RadioGroup, only one RadioButton can be set as checked.
A RadioButton is defined in the xml in the following manner:

RadioButton是可以设置为选中或未选中状态的小部件。 选中RadioButton后,您将无法取消选中它,除非RadioGroup内部存在该按钮。
RadioGroup是保存RadioButtons的容器。 一次在RadioGroup中,只能将一个RadioButton设置为选中状态。
通过以下方式在xml中定义RadioButton:

<RadioButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:onClick="androidlyRadioButton"
        android:text="Androidly RadioButtons"
        android:textSize="18sp" />

android:text is used to set the text of the RadioButton.
You can set the text gravity using the android:gravity attribute
android:onClick is used to set the function in the Kotlin activity to be triggered when the RadioButton is clicked.
android:buttonTint is used to set the color of the circular button. By default, it is set to the colorAccent specified in the styles.xml.

android:text用于设置RadioButton的文本。
您可以使用android:gravity属性设置文字重力
android:onClick用于将Kotlin活动中的功能设置为单击RadioButton时要触发的功能。
android:buttonTint用于设置圆形按钮的颜色。 默认情况下,它设置为styles.xml中指定的colorAccent。

To define a RadioButton programmatically we use:

要以编程方式定义RadioButton,请使用:

val radioButton = RadioButton(this)

A RadioGroup is defined in the following way in the XML.

在XML中以以下方式定义RadioGroup。

<RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:contentDescription="Layouts"
        android:orientation="vertical">

<RadioButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:onClick="androidlyRadioButton"
        android:text="Androidly RadioButtons"
        android:textSize="18sp" />

.
.
.
.
</RadioGroup>

Setting the orientation on the RadioGroup would lay the RadioButtons in that order(horizontally/vertically).

在RadioGroup上设置方向将按该顺序(水平/垂直)放置RadioButton。

To define a RadioGroup programmatically, we do:

要以编程方式定义RadioGroup,我们需要执行以下操作:

val radioButton = RadioButton(this)
val radioGroup = RadioGroup(this)
radioGroup.addView(radioButton)

This adds a single RadioButton inside the RadioGroup.

这将在RadioGroup内部添加单个RadioButton。

A RadioGroup can set Layout Weights similar to a LinearLayout.
We use the attribute android:weightSum on the RadioGroup and android:layout_weight on the RadioButton(s).

RadioGroup可以设置类似于LinearLayout的布局权重。
我们在RadioGroup上使用android:weightSum属性,在RadioButton上使用android:layout_weight

To clear ALL states from a RadioGroup we need to invoke the following in our Kotlin Activity class.

要从RadioGroup清除所有状态,我们需要在Kotlin Activity类中调用以下内容。

radioGroup.clearCheck()

RadioGroup Listener
In our activity, we can use the RadioGroup.OnCheckChangedListener interface callback to listen for changes in the states of the RadioButtons held inside the RadioGroup.

RadioGroup侦听器
在我们的活动中,我们可以使用RadioGroup.OnCheckChangedListener接口回调来侦听RadioGroup内部保存的RadioButtons状态的变化。

radioGroup.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { radioGroup, i ->
            textView.text = "option "+i+" is selected"
        })

radioGroup argument is the current radiogroup and i is the id of the RadioButton present in that RadioGroup.

radioGroup参数是当前的无线电组,而i是该RadioGroup中存在的RadioButton的ID。

In the following section, we’ll be creating a Single View Application that hosts RadioGroups from the XML as well as programmatically. We’ll display a Toast whenever any of the RadioButtons is checked.

在下一节中,我们将创建一个单视图应用程序,该应用程序可以通过XML以及以编程方式托管RadioGroup。 每当选中任何RadioButton时,我们都会显示Toast。

项目结构 (Project Structure)

布局代码 (Layout Code)

The code for the activity_main.xml layout is given below:

下面给出了activity_main.xml布局的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">


    <RadioButton
        android:id="@+id/androidlyRadioButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:onClick="androidlyRadioButton"
        android:text="Androidly RadioButtons"
        android:textSize="18sp" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Which layout has child views on top of each other?"
        android:textSize="20sp" />


    <RadioGroup
        android:id="@+id/firstRg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:contentDescription="Layouts"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="LinearLayout"
            android:textSize="18sp" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:buttonTint="@color/colorPrimary"
            android:text="RelativeLayout"
            android:textSize="18sp" />

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="FrameLayout"
            android:textColor="#99cc00"
            android:textSize="18sp" />

        <RadioButton
            android:id="@+id/radioButton4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="TableLayout"
            android:textSize="18sp" />

    </RadioGroup>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Which of the following are clickable?"
        android:textSize="20sp" />


    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear Groups" />


</LinearLayout>

活动代码 (Activity Code)

The code for the MainActivity.kt class is given below:

MainActivity.kt类的代码如下:

package net.androidly.androidlyradiobuttons

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*


class MainActivity : AppCompatActivity(), RadioGroup.OnCheckedChangeListener {


    val buttonTexts = arrayListOf("Buttons", "Text", "Both")

    val ID = 101

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val secondRg = RadioGroup(this)
        secondRg.orientation = RadioGroup.HORIZONTAL
        secondRg.weightSum = 3f
        secondRg.id = ID
        secondRg.contentDescription = "Widgets"
        secondRg.setOnCheckedChangeListener(this)
        linearLayout.firstRg.setOnCheckedChangeListener(this)



        val p = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        p.weight = 0.5f

        for (i in 0 until buttonTexts.size) {
            val radioButton = RadioButton(this)
            radioButton.apply {
                text = buttonTexts[i]
                id = i
                layoutParams = p
            }
            secondRg.addView(radioButton)
        }

        linearLayout.addView(secondRg, 4)

        button.setOnClickListener {
            secondRg.clearCheck()
            linearLayout.firstRg.clearCheck()
        }
    }

    override fun onCheckedChanged(group: RadioGroup?, checkId: Int) {
        val checkedRadioButton = group?.findViewById(group.checkedRadioButtonId) as? RadioButton
        checkedRadioButton?.let {

            if (checkedRadioButton.isChecked)
                Toast.makeText(applicationContext, "RadioGroup: ${group?.contentDescription} RadioButton: ${checkedRadioButton?.text}", Toast.LENGTH_LONG).show()
        }

    }

    fun androidlyRadioButton(view: View) {


        val radioButton = view as RadioButton
        Toast.makeText(applicationContext, "Radio Button: ${radioButton.text}", Toast.LENGTH_LONG).show()
    }
}

In the above code, we’ve created a Second RadioGroup which holds the RadioButtons horizontally.
We’ve implemented RadioGroup.OnCheckedChangeListener interface on our Activity.
androidlyRadioButton is triggered when the single RadioButton defined in the layout gets checked.
We need to typecast it from View to RadioButton.
fun onCheckedChanged(group: RadioGroup?, checkId: Int) is what gets triggered everytime a RadioButton from any of the RadioGroups gets checked or unchecked.
checkedRadioButtonId property is used to get the ID of the RadioButton that was selected.
We use the isChecked property on the RadioButton to display a Toast only when a RadioButton gets checked.

在上面的代码中,我们创建了第二个RadioGroup,它水平放置RadioButtons。
我们已经在Activity上实现了RadioGroup.OnCheckedChangeListener接口。
当检查布局中定义的单个RadioButton时,将触发androidlyRadioButton。
我们需要将其从View转换为RadioButton。
fun onCheckedChanged(group: RadioGroup?, checkId: Int)是每次检查或取消选中任何RadioGroup中的RadioButton时触发的内容。
checkedRadioButtonId属性用于获取选定的RadioButton的ID。
我们仅在选中RadioButton时才使用RadioButton的isChecked属性显示Toast。

The output of the above application in action is given below:

android-kotlin-radiobutton-output

上面应用程序的输出如下:

This brings an end to this tutorial. You can download the AndroidlyRadioButtons Project from the link below.

本教程到此结束。 您可以从下面的链接下载AndroidlyRadioButtons项目

翻译自: https://www.journaldev.com/37762/android-radiobutton-radiogroup-using-kotlin

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值