Android笔记(五):Android中的Radio
16lz
2021-01-26
原文地址:http://irving-wei.iteye.com/blog/1076097
上篇介绍了CheckBox,这节,将接触到的是RadioGroup和RadioButton。
它们的关系是:一个RadioGroup对应多个RadioButton,而一个RadioGroup中的RadioButton只能同时有一个被选中,它的选中值就是该RadioGroup的选中值。
这一节的代码运行效果图如下所示:
具体的代码编写过程如下:
首先在strings.xml中添加本程序所要用到的字符串:
- <?xmlversion="1.0"encoding="utf-8"?>
- <resources>
- <stringname="hello">HelloWorld,Test!</string>
- <stringname="app_name">AndroidWithRadioGroup</string>
- <stringname="radio_1">帅哥</string>
- <stringname="radio_2">美女</string>
- <stringname="question">请问你的性别是?</string>
- </resources>
接下来就是在main.xml中添加一个显示信息的TextView和一个RadioGroup,该RadioGroup包含两个RadioButton,代码如下:
- <TextView
- android:id="@+id/showText"
- android:layout_width="228px"
- android:layout_height="49px"
- android:text="@string/question"
- android:textSize="20sp"
- />
- <!--建立一个radioGroup-->
- <RadioGroup
- android:id="@+id/radioGroup"
- android:layout_width="137px"
- android:layout_height="216px"
- android:orientation="horizontal"
- >
- <!--建立一个RadioButton-->
- <RadioButton
- android:id="@+id/radioButton1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/radio_1"
- />
- <!--建立第二个RadioButton-->
- <RadioButton
- android:id="@+id/radioButton2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/radio_2"
- />
- </RadioGroup>
接下来就是在Activity的子类中,获取到以上定义的三个组件,而后给RadioGroup添加上OnCheckedChangeListener并实现监听方法。
代码如下:
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- textView=(TextView)findViewById(R.id.showText);
- radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
- radioButton1=(RadioButton)findViewById(R.id.radioButton1);
- radioButton2=(RadioButton)findViewById(R.id.radioButton2);
- radioGroup.setOnCheckedChangeListener(newOnCheckedChangeListener(){
- publicvoidonCheckedChanged(RadioGroupgroup,intcheckedId){
- if(checkedId==radioButton1.getId()){
- textView.setText(radioButton1.getText());
- }elseif(checkedId==radioButton2.getId()){
- textView.setText(radioButton2.getText());
- }
- }
- });
更多相关文章
- Android(安卓)Camera 系统 imx代码
- 7.1.5 选项卡结合案例详解
- 用cordova打包web项目
- ActionBar 自定义布局定义
- Android支付宝支付封装代码
- Android实现3秒钟自动关闭界面
- Open Core 上层代码结构
- 利用 Android(安卓)Studio 和 Gradle 打包多版本APK
- android 使用uinput模拟输入设备的方法