Android笔记(五):Android中的Radio

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

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


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

[img]http://dl.iteye.com/upload/attachment/496620/5734fa2c-faf5-36d8-976a-51581985b270.jpg[/img]

具体的代码编写过程如下:
首先在strings.xml中添加本程序所要用到的字符串:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Test!</string>
<string name="app_name">AndroidWithRadioGroup</string>
<string name="radio_1">帅哥</string>
<string name="radio_2">美女</string>
<string name="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(new OnCheckedChangeListener() {

public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == radioButton1.getId()) {
textView.setText(radioButton1.getText());
} else if (checkedId == radioButton2.getId()) {
textView.setText(radioButton2.getText());
}
}
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值