RadiButton 为单选样式,需与 RadioGroup 结合使用。
常用属性
<RadioGroup
android:id="@+id/rg_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/rc_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"
android:checked="true"
android:textSize="18dp"
android:textColor="#ff6600"/>
<RadioButton
android:id="@+id/rb_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"
android:textColor="#ff6600"
android:textSize="18dp"/>
</RadioGroup>
其中:
checked = “true” 默认选中(注:若使用该属性则必须设置每个选项的id,否则会导致该属性失效)
自定义样式
自定义样式文件:
<selector xmlns:...>
<!--被选中时的样式-->
<!--棕色实心矩形圆角矩形-->
<item android:state_checked="true">
<shape>
<solid android:color="#aa6600"/>
<corners android:radius="5dp"/>
</shape>
</item>
<!--未被选中时的样式-->
<!--棕色空心矩形圆角矩形框-->
<item android:state_checked="false">
<shape>
<stroke android:width="1dp"
android:color="#aa6600"/>
<corners android:radius="5dp"/>
</shape>
</item>
</selector>
调用自定义样式表的 RadioButton 部分代码:
<RadioGroup
android:id="@+id/rg_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="@+id/rg_1">
<RadioButton
...
android:gravity="center"
android:text="男"
android:button="@null"
android:background="@drawable/selector_orange_radiobutton"
android:checked="true"
.../>
<RadioButton
...
android:gravity="center"
android:text="女"
android:button="@null"
android:background="@drawable/selector_orange_radiobutton"
.../>
</RadioGroup>
其中:
button = “@null” 隐藏单选框前默认的button
background="@drawable/selector_orange_radiobutton" 将RadioButton的背景设置为自定义的样式
监听事件
RadioButtonActivity.java 文件监听事件部分代码:
//声明控件
private RadioGrounp mRg1;
//找到控件
mRg1 = (RadioGroup) findViewById(R.id.rg_1);
//设置监听事件
mRg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup group, int checkedId){
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
Toast.makeText(RadioButtonActivity.this, radioButton.getText(), Toast.LENGTH_SHORT).show();
}
});