//布局
< RadioGroupandroid: id= " @+id/rb" android: layout_width= " match_parent" android: layout_height= " 44dp" android: orientation= " horizontal" > <RadioButtonandroid:id="@+id/rb_start"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:background="@drawable/selector_bg"android:button="@null"//去除圆心android:checked="true"//默认选中该buttonandroid:gravity="center"android:text="开始"android:textColor="@drawable/selector_text_color" />< RadioButtonandroid: 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
<?xml version="1.0" encoding="utf-8"?>
< 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
<?xml version="1.0" encoding="utf-8"?>
< 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
<?xml version="1.0" encoding="utf-8"?>
< 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
<?xml version="1.0" encoding="utf-8"?>
< shape xmlns: android= " http://schemas.android.com/apk/res/android" android: shape= " rectangle" > < solid android: color= " #008577" /> < corners android: radius= " 5dp" />
</ shape>
rbEnd. setButtonDrawable ( new StateListDrawable ( ) ) ;
点击任意RadioButton只能选中固定的RadioButton
rb. setOnCheckedChangeListener ( ( RadioGroup group, @IdRes int checkedId) -> { rb. check ( R . id. rb_start) ;
} ) ;
rbStart. setEnabled ( false ) ;
代码设置RadioButton的textColor属性,可以根据是否选中按钮展示不同颜色
int [ ] [ ] states = new int [ ] [ ] { new int [ ] { - android. R. attr. state_checked} , new int [ ] { android. R. attr. state_checked}
} ;
int [ ] colors = new int [ ] { 0xFF000000 , 0xFFFFFFFF ,
} ;
ColorStateList colorStateList = new ColorStateList ( states, colors) ;
rbStart. setTextColor ( colorStateList) ;
rbEnd. setTextColor ( colorStateList) ;
示例