第25页
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
RadioButton组件的android:checked属性用于指定选中状态,属性值为true时,表示选中;属性值为false时,表示取消选中,默认为false。
通常情况下,RadioButton组件需要与RadioGroup组件一起使用,组成一个单选按钮组。在XML布局文件中,添加RadioGroup组件的基本格式如下:
android:id="@+id/radioGroup1"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
例3.14 在Eclipse中创建Android项目,名称为3.14,实现在屏幕上添加选择性别的单选按钮组。(实例位置:光盘\TM\sl\3\3.14)
修改新建项目的res\layout目录下的布局文件main.xml,将默认添加的垂直线性布局管理器设置为水平布局管理器,在该布局管理器中添加一个TextView组件、一个包含两个单选按钮的单选按钮组和一个用于提交的按钮,具体代码如下:
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/background">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="性别:"
android:height="50px" />
android:id="@+id/radioGroup1"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
android:layout_height="wrap_content"
android:id="@+id/radio0"
android:text="男"
android:layout_width="wrap_content"
android:checked="true"/>
android:layout_height="wrap_content"
android:id="@+id/radio1"
android:text="女"
android:layout_width="wrap_content"/>
运行本实例,将显示如图3.19所示的运行结果。
图3.19 添加选择性别的单选按钮组
在屏幕中添加单选按钮组后,还需要获取单选按钮组中选中项的值,通常存在以下两种情况:一种是在改变单选按钮组的值时获取;另一种是在单击其他按钮时获取。下面分别介绍这两种情况所对应的实现方法。
[√]在改变单选按钮组的值时获取
在改变单选按钮组的值时获取选中项的值时,首先需要获取单选按钮组,然后为其添加OnCheckedChangeListener,并在其onCheckedChanged()方法中根据参数checkedId获取被选中的单选按钮,并通过其getText()方法获取该单选按钮对应的值。例如,要获取id属性为radioGroup1的单选按钮组的值,可以通过下面的代码实现。
RadioGroup sex=(RadioGroup)findViewById(R.id.radioGroup1);
sex.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton r=(RadioButton)findViewById(checkedId);
r.getText(); //获取被选中的单选按钮的值
}
});
[√]单击其他按钮时获取
单击其他按钮时获取选中项的值时,首先需要在该按钮的单击事件监听器的onClick()方法中,通过for循环语句遍历当前单选按钮组,并根据被遍历到的单选按钮的isChecked()方法判断该按钮是否被选中,当被选中时,通过单选按钮的getText()方法获取对应的值。例如,要在单击“提交”按钮时,获取id属性为radioGroup1的单选按钮组的值,可以通过下面的代码实现。
final RadioGroup sex=(RadioGroup)findViewById(R.id.radioGroup1);
Button button=(Button)findViewById(R.id.button1); //获取一个提交按钮
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for(int i=0;i
RadioButton r=(RadioButton)sex.getChildAt(i); //根据索引值获取单选按钮
if( r.isChecked() ){ //判断单选按钮是否被选中
r.getText(); //获取被选中的单选按钮的值