1.Radiobutton 和 Radiogroup的解析(单选框)
Radiobutton 是一个单选按钮,它表示一组选项中的一个。它通常与其他 Radiobutton 控件组合在一起,形成一个 Radiogroup。
Radiogroup 是一个容器控件,用于将多个 Radiobutton 组织在一起。Radiogroup 保证了其中的 Radiobutton 只能选择一个,即单选功能。 注意:Radiogroup具有和LinearLayout一样的横向属性(android:orientation="horizontal")和垂直属性(android:orientation="vertical")
2.Radiobutton的常用属性:
- android:enabled:指定 Radiobutton 是否可用,值为 "true" 或 "false"
- android:checked:指定 Radiobutton 的初始选中状态,值为 "true" 或 "false"
3.示例代码效果
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="单选"/>
<RadioGroup
android:id="@+id/sex"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"
android:checked="true"
android:id="@+id/sex_boy"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"
android:id="@+id/sex_girl"/>
</RadioGroup>
findcheck();
sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.sex_boy:
Toast.makeText(RadiogroupActivity.this,"男", Toast.LENGTH_SHORT).show();
break;
case R.id.sex_girl:
Toast.makeText(RadiogroupActivity.this,"女", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
private void findcheck(){
sex=findViewById(R.id.sex);
}