簡述RadioGroup和RadioButton的使用
在項目中有身份選擇的選項,需要用到RadioGroup和RadioButton,這里做個記錄,和大家交流一下。
話不多說,一起看代碼
XML代碼
<RadioGroup android:id="@+id/login_radiogroup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="horizontal">
<RadioButton android:id="@+id/admin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="@string/admin"/>
<RadioButton android:id="@+id/tech" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="@string/tech"/>
<RadioButton android:id="@+id/market" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="@string/market"/>
<RadioButton android:id="@+id/guest" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="@string/guest"/>
</RadioGroup>
這里使用了layout_gravity讓RadioGroup居中顯示,使用了orientation屬性,horizontal讓內部的RadioButton呈水平擺放,vertical就是垂直擺放。
JAVA代碼
這里因為在Fragment里面實例化布局,所有用了view.findViewById(),在Activity中的話去掉view就可以。
private RadioGroup mRadioGroup;
mRadioGroup=(RadioGroup)view.findViewById(R.id.login_radiogroup);
接下來在活動中實現對RadioGroup的監聽。
1 mRadioGroup.setOnCheckedChangeListener(new CheckListener()); 2 3 class CheckListener implements RadioGroup.OnCheckedChangeListener{ 4 5 @Override 6 public void onCheckedChanged(RadioGroup group, int checkedId) { 7 switch (checkedId){ 8 case R.id.admin: 9 //執行具體操作 10 break; 11 12 case R.id.tech: 13 //執行具體操作 14 break; 15 16 case R.id.market: 17 //執行具體操作 18 break; 19 20 case R.id.guest: 21 //執行具體操作 22 break; 23 24 default: 25 break; 26 27 } 28 } 29 }
是個菜鳥,有錯誤還希望大家能指出來。
歡迎大家有好的想法一起交流。