RadioGroup,Android的單選框。

在安卓上,實現單選框。
先看一下需求:在用戶註冊頁面需要填性別項,大家知道性別不是男的便是女的。(這裏不考慮其它情況)這時候單選框就派上用場了,先看佈局文件。

<?xml version="1.0" encoding="utf-8"?>
<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");
            }
        }
    };
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章