RadioButton监听事件

RadioButton为单选按钮,他需要与RadioGroup配合使用

    对应的布局代码:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:app="http://schemas.android.com/apk/res-auto"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     tools:context=".MainActivity"
 8     android:orientation="vertical">
 9 
10   <TextView
11       android:id="@+id/t1"
12       android:layout_width="match_parent"
13       android:layout_height="wrap_content"
14       android:gravity="center"
15       android:text="input"
16       android:textSize="25sp" />
17   <RadioGroup
18       android:id="@+id/rg"
19       android:layout_width="wrap_content"
20       android:layout_height="wrap_content"
21       android:orientation="vertical">
22     <RadioButton
23         android:id="@+id/rba"
24         android:layout_width="wrap_content"
25         android:layout_height="wrap_content"
26         android:text="A"
27         />
28     <RadioButton
29         android:id="@+id/rbb"
30         android:layout_width="wrap_content"
31         android:layout_height="wrap_content"
32         android:text="B"
33         />
34     <RadioButton
35         android:id="@+id/rbc"
36         android:layout_width="wrap_content"
37         android:layout_height="wrap_content"
38         android:text="C"
39         />
40     <RadioButton
41         android:id="@+id/rbd"
42         android:layout_width="wrap_content"
43         android:layout_height="wrap_content"
44         android:text="D"
45         />
46   </RadioGroup>
47 </LinearLayout>

Java代码:

 1 package com.example.administrator.myapplication;
 2 
 3 import android.support.v7.app.AppCompatActivity;
 4 import android.os.Bundle;
 5 import android.view.View;
 6 import android.widget.RadioButton;
 7 import android.widget.RadioGroup;
 8 import android.widget.TextView;
 9 import android.widget.Toast;
10 
11 public class MainActivity extends AppCompatActivity {
12    TextView t;
13     @Override
14     protected void onCreate(Bundle savedInstanceState) {
15         super.onCreate(savedInstanceState);
16         setContentView(R.layout.activity_main);
17 
18         t=findViewById(R.id.t1);
19         RadioGroup rg = findViewById(R.id.rg);
20         rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
21             @Override
22             public void onCheckedChanged(RadioGroup radioGroup, int checkdId) {
23                 RadioButton rb = findViewById(checkdId);
24                 String s = rb.getText().toString();
25                 t.setText("单击了" +s);
26             }
27         });
28     }
29 }

在上述代码中,利用setCheckedChangeListener()监听RadioGroup控件状态,获取监听结果输出到TextView控件里显示

原文地址:https://www.cnblogs.com/xfweb/p/10559922.html