天天看點

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 RadioButton,使用Kotlin的RadioGroup

上面應用程式的輸出如下:

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

本教程到此結束。 您可以從下面的連結下載下傳AndroidlyRadioButtons項目 。

AndroidlyRadioButtons AndroidlyRadioButtons

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