一起Talk Android吧(第七十回:Android中UI控件之RadioButton)


各位看官们,大家好,上一回中咱们说的是Android中UI控件之Button可变性的例子,这一回咱们说的例子是UI控件之RadioButton。闲话休提,言归正转。让我们一起Talk Android吧!

看官们,RadioButton也叫单选按钮。它通常用来给用户提供单选操作,程序依据用户选择的操作来做不同的事情。接下来我们通过代码结合文本的方式来演示使用使用这种组件。

  • 1.在布局中添加RadioGroupRadioButton。通常是在Activity或者Fragment的布局文件中添加。
  <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView //这个文本控件是用来给用户选择的内容做提示,提示的内容就是文本显示的内容
                android:layout_width="60dp"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="Sex: "/>

        <RadioGroup //添加RadioGroup控件,并且设置它的id等属性
            android:id="@+id/radio_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RadioButton  //添加RadioButton控件,并且设置它的id等属性
                android:id="@+id/radio_bt_male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"  //表示默认选中该控件
                android:text="Male"/>
            <RadioButton  //添加RadioButton控件,并且设置它的id等属性
                android:id="@+id/radio_bt_female"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Female" />
        </RadioGroup>
    </LinearLayout>

在上面的代码中,我们添加了一个RadioGroup,并且在它里面添加了两个RadioButton控件,用户只能在这两个控件中选择一个。当然也可以添加多个RadioButton控件,但是用户只能选择其中的一个。此外,我们还修改了RadioButton控件的checked属性,该属性默认值为false,表示RadioButton没有被选中。如果将其值修改为true,那么表示默认选中。

  • 2.在代码中获取布局文件中的RadioGroup。通常位于Activity或者Fragment的onCreate方法中。
 private RadioGroup mRadioGroup = (RadioGroup)findViewById(R.id.radio_group);
  • 3.在代码中获取用户选择了RadioGroup中的哪个RadioButton。通常是在RadioGroup的监听器中来完成该操作。
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.radio_bt_male:
                        Toast.makeText(getApplicationContext(),"Select Male",Toast.LENGTH_LONG).show();
                        break;
                    case R.id.radio_bt_female:
                        Toast.makeText(getApplicationContext(),"Select Female",Toast.LENGTH_LONG).show();
                        break;
                        default:
                            break;
                }
            }
        });

在上面的代码中,我们为RadioGroup设置了监听器,并且重写了监听器中的onCheckedChanged()方法。当用户选择RadioGroup中任何一个RadioButton时都会触发该监听器,至于用户选择了哪个RadioButton,我们可以通过onCheckedChanged()方法的第二个参数来判断,它传递来的数值就是RadioGroup中某个RadioButton的id。

运行上面的代码时,当用户选择了某个RadioButton,就会弹出一个对应的来提示。下面是程序的运行截图,请大家参考。

这里写图片描述

各位看官,关于Android中UI控件之RadioButton的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!


猜你喜欢

转载自blog.csdn.net/talk_8/article/details/79763197