Android系統(tǒng)控件CheckBox是一個同時可以選擇多個選項的控件;而RadioButton則是僅可以選擇一個選項的控件;RadioGroup是RadioButton的承載體,程序運行時不可見,應(yīng)用程序中可能包含一個或多個RadioGroup,一個RadioGroup包含多個RadioButton,在每個RadioGroup中,用戶僅能夠選擇其中一個RadioButton。
下面就通過一個例子來加深對這兩個控件的理解,其效果如圖-1所示。

圖-1 CheckBox與RadioButton效果圖
1.建立一個“CheckboxRadiobuttonDemo”程序
程序包含5個控件,從上至下分別是TextView01、CheckBox01、 CheckBox02、RadioButton01、RadioButton02,當(dāng)選擇RadioButton01時,RadioButton02則無法選擇。
CheckboxRadiobuttonDemo在XML文件中的代碼如代碼清單1所示。
代碼清單1 main.xml
<TextView android:id="@+id/TextView01“
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
<CheckBox android:id="@+id/CheckBox01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox01" >
</CheckBox>
<CheckBox android:id="@+id/CheckBox02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox02" >
</CheckBox>
<RadioGroup android:id="@+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton android:id="@+id/RadioButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton01" >
</RadioButton>
<RadioButton android:id="@+id/RadioButton02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton02" >
</RadioButton>
</RadioGroup>
上述代碼中,第15行標(biāo)簽聲明了一個RadioGroup;在第18行和第23行分別聲明了兩個RadioButton,這兩個RadioButton是RadioGroup的子元素。
2.引用CheckBox和RadioButton
引用CheckBox和RadioButton的方法參考代碼清單2所示的代碼。
代碼清單2 引用CheckBox和RadioButton
CheckBox checkBox1= (CheckBox)findViewById(R.id.CheckBox01);
RadioButton radioButton1 =(RadioButton)findViewById(R.id.RadioButton01);
3.響應(yīng)點擊事件:添加點擊事件的監(jiān)聽器
CheckBox設(shè)置點擊事件監(jiān)聽器的方法與Button設(shè)置點擊事件監(jiān)聽器中介紹的方法相似,唯一不同在于將Button.OnClickListener換成了CheckBox.OnClickListener。
代碼清單3 設(shè)置CheckBox點擊事件監(jiān)聽器
CheckBox.OnClickListener checkboxListener = new CheckBox.OnClickListener(){
@Override
public void onClick(View v) {
//過程代碼
}};
checkBox1.setOnClickListener(checkboxListener);
checkBox2.setOnClickListener(checkboxListener);
RadioButton設(shè)置點擊事件監(jiān)聽器的方法如代碼清單4所示。
代碼清單4 設(shè)置RadioButton點擊事件監(jiān)聽器
RadioButton.OnClickListener radioButtonListener = new RadioButton.OnClickListener(){
@Override
public void onClick(View v) {
//過程代碼
}};
radioButton1.setOnClickListener(radioButtonListener);
radioButton2.setOnClickListener(radioButtonListener);
通過上述的講解,可以得出這樣的結(jié)論:CheckBox是可以選擇多個選項的復(fù)選框控件,當(dāng)其中選項被選中時,顯示相應(yīng)的checkmark。這時,需要創(chuàng)建一個“OnClickListener”捕獲點擊事件,并可以添加所需的功能代碼。
RadioGroup是一個包含一些RadioButton的ViewGroup。用戶可選擇一個按鈕,通過對每一個RadioButton設(shè)置監(jiān)聽OnClickListeners來獲取其選擇。這里需注意,點擊RadioButton并不觸發(fā)RadioGroup的Click事件。