概述
这节课来讲RadioButton,那RadioButton长什么样子呐?通常来讲在一个App中选择性别男和女,这个就是一个Radiobutton来实现的。因为这是在一组中选一个,一组中单选就是用RadioButton,当然要结合RadioGroup结合使用。首先讲一些常用的属性。还有自定义的样式,我们毕竟要根据实际的设计稿来自定义RadioButton样式。最后监听事件,如何监听RadioButton选中事件,我们才能获得当前选中的值。
演示
1、添加一个RadioButton组件,id为1,文字内容为男,橙色,左边的圆圈可以选中
<RadioButton
android:id="@+id/rb_1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="男"
android:textSize="20sp"
android:textColor="#FF6600"/>
2、做一个男女单选,使用RadioGroup组件,因为RadioGroup可以水平和垂直,这里设置成垂直,因为这两个在一个组中,只能单选
<RadioGroup
android:id="@+id/rg_1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/rb_1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="男"
android:textSize="20sp"
android:textColor="#FF6600"/>
<RadioButton
android:id="@+id/rb_2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="女"
android:textSize="20sp"
android:textColor="#FF6600"/>
</RadioGroup>
3、添加一个开始自动选中效果,自动选中男
android:checked="true"
4、自定义效果,新建radiobutton.xml文件作为背景效果,选中是深色橙色背景,未选中是橙色描边,android:button="@null"为去掉默认的圆圈,android:gravity="center"文字居中,android:state_checked是否选中 activity_main.xml:
<RadioGroup
android:id="@+id/rg_2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_below="@id/rg_1">
<RadioButton
android:id="@+id/rb_3"
android:layout_height="30dp"
android:layout_width="60dp"
android:text="男"
android:button="@null"
android:checked="true"
android:gravity="center"
android:background="@drawable/radiobutton"
android:textSize="20sp"
android:textColor="#000"/>
<RadioButton
android:id="@+id/rb_4"
android:layout_height="30dp"
android:layout_width="60dp"
android:text="女"
android:button="@null"
android:gravity="center"
android:layout_marginTop="5dp"
android:background="@drawable/radiobutton"
android:textSize="20sp"
android:textColor="#000"/>
</RadioGroup>
radiobutton.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape>
<solid android:color="#AA6600"/>
<corners android:radius="5dp"/>
</shape>
</item>
<item android:state_checked="false">
<shape>
<stroke android:color="#FF9900"
android:width="1dp"/>
<corners android:radius="5dp"/>
</shape>
</item>
</selector>
5、添加监听事件,在第一组radiogroup中添加 HelloAndroidActivity.java:
private RadioGroup mrg1;
mrg1 = (RadioGroup)findViewById(R.id.rg_1);
mrg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
RadioButton radiobutton = (RadioButton)group.findViewById(checkedId);
Toast.makeText(HelloAndroidActivity.this,radiobutton.getText(), Toast.LENGTH_SHORT).show();
}
});