RadioGroup 使用

  • xml
//布局
<RadioGroup
    android:id="@+id/rb"
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:orientation="horizontal">

    

	<RadioButton
	    android:id="@+id/rb_end"
	    android:layout_width="0dp"
	    android:layout_height="match_parent"
	    android:layout_weight="1"
	    android:background="@drawable/selector_bg"
	    android:button="@null"
	    android:gravity="center"
	    android:text="结束"
	    android:textColor="@drawable/selector_text_color" />
RadioGroup>

//selector_text_color.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#FF008577" android:state_checked="false" />
    <item android:color="#FFFFFFFF" android:state_checked="true" />
selector>

//selector_bg.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/shape_bg_true" android:state_checked="true" />
    <item android:drawable="@drawable/shape_bg_false" android:state_selected="false" />
selector>

//shape_bg_true.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#D81B60" />
    <corners android:radius="5dp" />
shape>

//shape_bg_false.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#008577" />
    <corners android:radius="5dp" />
shape>
  • 去除RadioButton圆心
//1.在xml布局中加入android:button="@null"
//2.某些机型上在xml中设置不会起作用,可以使用代码设置
rbEnd.setButtonDrawable(new StateListDrawable());
  • 点击任意RadioButton只能选中固定的RadioButton
rb.setOnCheckedChangeListener((RadioGroup group, @IdRes int checkedId) -> {
    //点击某个RaidoButton的时候,RadioGroup会执行该回调方法,设置自己想要的button为选中状态.
    rb.check(R.id.rb_start);
});
  • 使RadionButton失去点击效果
rbStart.setEnabled(false);
  • 代码设置RadioButton的textColor属性,可以根据是否选中按钮展示不同颜色
int[][] states = new int[][]{
        new int[]{-android.R.attr.state_checked}, // unchecked
        new int[]{android.R.attr.state_checked}  // checked
};
int[] colors = new int[]{
        0xFF000000,// unchecked
        0xFFFFFFFF,// checked
};
ColorStateList colorStateList = new ColorStateList(states, colors); 
rbStart.setTextColor(colorStateList);
rbEnd.setTextColor(colorStateList);
示例

s, colors);
rbStart.setTextColor(colorStateList);
rbEnd.setTextColor(colorStateList);


##### 示例
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190923115841397.gif)

你可能感兴趣的:(RadioGroup 使用)