一、RadioButton和 CheckBox都是可选框控件,我们先说下他们两个的区别:
1、RadioButton 单选框,无法通过点击切换选中状态。
CheckBox 多选框,可以通过点击切换选中状态。
二、RadioButton 和 RadioGroup的关系:
1、RadioButton表示单选框,而RadioGroup是容纳多个RadioButton的容器
2、每个RadioGroup中的RadioButton只能有一个被选中
3、不同的RadioGroup中的RadioButton互不相干,即如果组A中有一个选中了,组B中依然可以有一个被选中
4、通常一个RadioGroup中至少有2个RadioButton
5、通常一个RadioGroup中的RadioButton默认会有一个被选中,建议将默认的放在RadioGroup中的起始位置
三、示例:
layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tv_gender_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="你选择的性别是:"
android:textColor="@android :color/white" />
<RadioGroup
android:id="@+id/re_sel_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_gender_msg"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_tip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left|center"
android:text="性别"
android:textColor="@android:color/white"
android:textSize="16sp" />
<RadioButton
android:id="@+id/rg_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="男"
android:textColor="@android:color/white"
android:textSize="16sp" />
<RadioButton
android:id="@+id/rg_famale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"
android:textColor="@android:color/white"
android:textSize="16sp" />
</RadioGroup>
</RelativeLayout>
Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
tvGenderMsg = (TextView) findViewById(R.id.tv_gender_msg);
RadioGroup rg = (RadioGroup) findViewById(R.id.re_sel_gender);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
setGenderMsg(checkedId);
}
});
setGenderMsg(rg.getCheckedRadioButtonId());
}
private void setGenderMsg(int checkedId) {
RadioButton rb = (RadioButton) findViewById(checkedId);
tvGenderMsg.setText("你选择的性别是:" + rb.getText());
}