学习完复选按钮,在来学习单选按钮(复选相对的就是单选嘛),这个按钮也比较简单,但是会用到一些组合组件的思想,大家可以认真体会!
基本用法
RadioButton经常会结合RadioGroup一起使用,实现多项单选功能的操作
<RadioGroup
android:id="@+id/job_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<RadioButton
android:id="@+id/radio_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="20dp"
android:text="程序员"
android:textColor="@color/colorPrimaryDark"
android:textSize="25sp" />
<RadioButton
android:id="@+id/radio_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="11dp"
android:text="政治家"
android:textColor="@color/colorPrimaryDark"
android:textSize="25sp" />
</RadioGroup>
组合用法
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//checkedId,表示的是选中的RadioButton的id,如果没写(动态加入的话),就是1到length的id
getYourFavorite(checkedId);
}
});
/**
* 根据ID,执行相应的逻辑
* @param buttonId
*/
private void getYourFavorite(int buttonId){
switch (buttonId){
case R.id.radio_button1:
//具体逻辑
break;
case R.id.radio_button2:
//具体逻辑
break;
case R.id.radio_button3:
//具体逻辑
break;
}
}
小tips
我们还可以通过调用clearCheck()实现清除选择状态。
radioGroup.clearCheck()
修改按钮样式是通过android:button属性:
<RadioButton
android:id="@+id/radio_button1"
android:button="@drawable/check_box_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="20dp"
android:text="程序员"
android:textColor="@color/colorPrimaryDark"
android:textSize="25sp" />
其中的check_box_back.xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/chosen"></item>
<item android:state_checked="false" android:drawable="@drawable/non_chosen_big"></item>
</selector>
总结一下设置图标的三种方式:
(1)button属性:主要用于图标大小要求不高,间隔要求也不高的场合。
(2)background属性:主要用于能够以较大空间显示图标的场合。
(3)drawableLeft属性:主要用于对图标与文字之间的间隔有要求的场合。设置图标与文字的距离,对应的属性为android:drawablePadding。
注意使用 background 或者 drawableLeft时 要设置 android:button="@null"
欢迎小伙伴们留言评论,指出文中的错误或者不足,非常感谢!