转载说明出处: http://blog.csdn.net/eana_don/article/details/8269632
RadioButton和CheckBox都继承了Button按钮,二者都可是直接使用Button支持的各种方法和属性。它们比一般的Button多出了一个可选的属性。在需要获取用户信息的应用中,有时候只需要提供用户选择和判断,并不需要用户的输入,这两种按钮就起到了用处。
一、RadioButton
xml写法:
<RadioGroup
android:id="@+id/radiogroup_gender"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<RadioButton
android:id="@+id/radiobtn_male"
android:text="男"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<RadioButton
android:id="@+id/radiobtn_female"
android:text="女"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RadioGroup>
代码监听控制:
radioGroup = (RadioGroup) findViewById(R.id.radiogroup_gender);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
RadioButton btn = (RadioButton) findViewById(group.getCheckedRadioButtonId());
Log.d("监听", "单选框点击 : "+ btn.getText());
}
});
运行界面:
二、CheckBox
xml写法:
<CheckBox
android:id="@+id/chkbox_red"
android:text="红色"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<CheckBox
android:id="@+id/chkbox_blue"
android:text="蓝色"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<CheckBox
android:id="@+id/chkbox_green"
android:text="绿色"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
代码监听控制:
chkbox_red = (CheckBox) findViewById(R.id.chkbox_red);
chkbox_blue = (CheckBox) findViewById(R.id.chkbox_blue);
chkbox_green = (CheckBox) findViewById(R.id.chkbox_green);
chkbox_red.setOnCheckedChangeListener(new CheckBoxListener());
chkbox_blue.setOnCheckedChangeListener(new CheckBoxListener());
chkbox_green.setOnCheckedChangeListener(new CheckBoxListener());
class CheckBoxListener implements android.widget.CompoundButton.OnCheckedChangeListener{
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
Log.d("监听", "复选框点击 : "+buttonView.getText());
}
}
运行界面: