-、区别: RadioButton只能单选 ,他外面要包含一个 radioButton控件。 而checkbox 能多选择。
RadioButton一般的形状是圆形的 而checkbox是正方形的。
RadioButton单选按钮是一种双状态的按钮,可以选择或不选中。在单选按钮 没有被选中时,用户能够按下或点击来选中它。但是,与复选框相反,用户一旦选中就 不能够通过界面取消选中,但是可以通过代码来取消选中状态。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RadioGroup
android:id="@+id/rgsex"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:checked="true"
android:id="@+id/rbman"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/strman"
/>
<RadioButton
android:id="@+id/rbwoman"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/strwoman"
/>
</RadioGroup>
<CheckBox
android:id="@+id/cbrun"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/strrun"/>
<CheckBox
android:id="@+id/cbswim"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/strswim"/>
<CheckBox
android:id="@+id/cbread"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/strread"/>
</LinearLayout>
然后就是添加事件了,RadioButton的事件添加在RadioGroup上面
rgsex=(RadioGroup)findViewById(R.id.rgsex);
rgsex.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId==R.id.rbman) {
makeToast(Radiobutton_Checkbox_MenuActivity.this,"你选择了男");
}else if (checkedId==R.id.rbwoman) {
makeToast(Radiobutton_Checkbox_MenuActivity.this,"你选择了女");
}
}
});
里面用到了一个makeToast方法,是我在下面定义的,就是弹出Toast提示。其他代码很简单,不做过多的说明了。注意它的OnCheckedChangeListener,因为下面也有一个。
然后添加CheckBox的事件,三个控件要依次添加方法,为了简便,实现以下这个借口。如下
//处理checkbox事件
cbrun=(CheckBox)findViewById(R.id.cbrun);
cbswim=(CheckBox)findViewById(R.id.cbswim);
cbread=(CheckBox)findViewById(R.id.cbread);
/*因为CompoundButton是checkbox的父类,这里用CompoundButton.OnCheckedChangeListener来绑定事件,
* 否则会和上面的radiogroup的事件冲突*/
CompoundButton.OnCheckedChangeListener listener=new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String str=buttonView.getText().toString();
if (isChecked) {
makeToast(Radiobutton_Checkbox_MenuActivity.this,str+"被选中");
}else {
makeToast(Radiobutton_Checkbox_MenuActivity.this,str+"被取消");
}
}
};
cbrun.setOnCheckedChangeListener(listener);
cbswim.setOnCheckedChangeListener(listener);
cbread.setOnCheckedChangeListener(listener);
自定义radiobutton样式并去掉默认的样式
android:button=“@null”
android:backgroup="@null"
在按钮的左边添加图片
android:drawableLeft="@drawable/male"
在按钮的右边添加图片
android:drawableRight="@drawable/radio_selector"
按钮与描述文字之间的距离
android:drawablePadding="10dp"