原文地址:http://irving-wei.iteye.com/blog/1076097

上篇介绍了CheckBox,这节,将接触到的是RadioGroup和RadioButton。

它们的关系是:一个RadioGroup对应多个RadioButton,而一个RadioGroup中的RadioButton只能同时有一个被选中,它的选中值就是该RadioGroup的选中值。


这一节的代码运行效果图如下所示:



具体的代码编写过程如下:
首先在strings.xml中添加本程序所要用到的字符串:

Xml代码
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <resources>
  3. <stringname="hello">HelloWorld,Test!</string>
  4. <stringname="app_name">AndroidWithRadioGroup</string>
  5. <stringname="radio_1">帅哥</string>
  6. <stringname="radio_2">美女</string>
  7. <stringname="question">请问你的性别是?</string>
  8. </resources>



接下来就是在main.xml中添加一个显示信息的TextView和一个RadioGroup,该RadioGroup包含两个RadioButton,代码如下:

Xml代码
  1. <TextView
  2. android:id="@+id/showText"
  3. android:layout_width="228px"
  4. android:layout_height="49px"
  5. android:text="@string/question"
  6. android:textSize="20sp"
  7. />
  8. <!--建立一个radioGroup-->
  9. <RadioGroup
  10. android:id="@+id/radioGroup"
  11. android:layout_width="137px"
  12. android:layout_height="216px"
  13. android:orientation="horizontal"
  14. >
  15. <!--建立一个RadioButton-->
  16. <RadioButton
  17. android:id="@+id/radioButton1"
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:text="@string/radio_1"
  21. />
  22. <!--建立第二个RadioButton-->
  23. <RadioButton
  24. android:id="@+id/radioButton2"
  25. android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:text="@string/radio_2"
  28. />
  29. </RadioGroup>



接下来就是在Activity的子类中,获取到以上定义的三个组件,而后给RadioGroup添加上OnCheckedChangeListener并实现监听方法。
代码如下:

Java代码
    1. super.onCreate(savedInstanceState);
    2. setContentView(R.layout.main);
    3. textView=(TextView)findViewById(R.id.showText);
    4. radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
    5. radioButton1=(RadioButton)findViewById(R.id.radioButton1);
    6. radioButton2=(RadioButton)findViewById(R.id.radioButton2);
    7. radioGroup.setOnCheckedChangeListener(newOnCheckedChangeListener(){
    8. publicvoidonCheckedChanged(RadioGroupgroup,intcheckedId){
    9. if(checkedId==radioButton1.getId()){
    10. textView.setText(radioButton1.getText());
    11. }elseif(checkedId==radioButton2.getId()){
    12. textView.setText(radioButton2.getText());
    13. }
    14. }
    15. });

更多相关文章

  1. Android(安卓)Camera 系统 imx代码
  2. 7.1.5 选项卡结合案例详解
  3. 用cordova打包web项目
  4. ActionBar 自定义布局定义
  5. Android支付宝支付封装代码
  6. Android实现3秒钟自动关闭界面
  7. Open Core 上层代码结构
  8. 利用 Android(安卓)Studio 和 Gradle 打包多版本APK
  9. android 使用uinput模拟输入设备的方法

随机推荐

  1. 桌面文件误删怎么找回
  2. 矩阵的乘法运算与css的3d变换(transform)
  3. PHP数据库操作:PDO基本操作
  4. 【Redis】PHP操作Redis的命令大全
  5. 解决Laravel5.5版本框架缺少vender目录报
  6. 闪存插入时显示提示格式化请问咋才能修复
  7. 误删的文件怎样找到
  8. 对查询的结果集添加自增序号
  9. 硬盘显示没有初始化恢复资料方法
  10. 写代码有这10个好习惯的话,可以减少80%非