当前位置: 移动技术网 > 移动技术>移动开发>Android > RadioButton监听事件

RadioButton监听事件

2019年03月20日  | 移动技术网移动技术  | 我要评论

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控件里显示

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网