簡述RadioGroup和RadioButton的使用

簡述RadioGroup和RadioButton的使用

在項目中有身份選擇的選項,須要用到RadioGroup和RadioButton,這裏作個記錄,和你們交流一下。android

話很少說,一塊兒看代碼ide

 

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就是垂直襬放。spa

 

 

JAVA代碼code

 

 

這裏由於在Fragment裏面實例化佈局,全部用了view.findViewById(),在Activity中的話去掉view就能夠。blog

 

private RadioGroup mRadioGroup;

 

 

 

 

mRadioGroup=(RadioGroup)view.findViewById(R.id.login_radiogroup);

 

 

 

 

 

接下來在活動中實現對RadioGroup的監聽。string

 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     }

 

 

 

是個菜鳥,有錯誤還但願你們能指出來。it

歡迎你們有好的想法一塊兒交流。io

相關文章
相關標籤/搜索