RadioGroup,Android的单选框。

在安卓上,实现单选框。
先看一下需求:在用户注册页面需要填性别项,大家知道性别不是男的便是女的。(这里不考虑其它情况)这时候单选框就派上用场了,先看布局文件。


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
       <RadioGroup
        android:id="@+id/sexRadioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="25dp"
        android:orientation="vertical" >

        <RadioButton
            android:id="@+id/man"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="男" />

        <RadioButton
            android:id="@+id/woman"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="女" />
    RadioGroup>


LinearLayout>

java代码:
初始化选择男性

    man.setChecked(true);

监听选择的选项

sexRadioGroup.setOnCheckedChangeListener(sexRadioGroupchange);

单选框监听器

    private RadioGroup.OnCheckedChangeListener sexRadioGroupchange= new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId==man.getId()) {
                log.d(TAG,"man");
            }else  {
                log.d(TAG,"woman");
            }
        }
    };

你可能感兴趣的:(控件,安卓开发)