在项目中,遇到过,甲方爸爸要求图片中圈圈的颜色跟着系统颜色改变,之前也没有做过类似的,翻找资料,好不容易做出来了。现在记下来,怕自己忘记
radio_button_selected.xml中
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape android:shape="oval">
<padding android:left="@dimen/list_item_radio_button_padding"
android:top="@dimen/list_item_radio_button_padding"
android:right="@dimen/list_item_radio_button_padding"
android:bottom="@dimen/list_item_radio_button_padding"/>
<stroke
android:width="2dp"
android:color="@color/color_black"/>
<size android:height="30dp"
android:width="30dp"/>
</shape>
</item>
<item android:id="@+id/radio_button_selected" >
<shape android:shape="oval">
<solid android:color="@color/color_purple"></solid>
</shape>
</item>
<item >
<shape android:shape="oval">
<padding android:left="@dimen/list_item_radio_button_padding"
android:top="@dimen/list_item_radio_button_padding"
android:right="@dimen/list_item_radio_button_padding"
android:bottom="@dimen/list_item_radio_button_padding"/>
<stroke
android:width="@dimen/list_item_radio_button_inner_border"
android:color="@color/color_white"/>
<size android:height="30dp"
android:width="30dp"/>
</shape>
</item>
</layer-list>
radio_button_default.xml中
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="@color/color_gray_light"/>
<stroke
android:width="@dimen/list_item_radio_button_border"
android:color="@color/color_black"/>
<size android:height="30dp"
android:width="30dp"/>
</shape>
LayerDrawable对应的XML的根元素是layer-list,它使一种层次化显示的Drawable集合
//在代码中创建selector,创建的类型是StateListDrawable,可以通过addState()为selector添加状态
//此外,在添加state中,在state前添加“-”号,表示此state为false(例如:-android.R.attr.state_selected),否则为true。
LayerDrawable layerDrawable = (LayerDrawable)ContextCompat.getDrawable(this, R.drawable.radio_button_selected);
GradientDrawable gradientDrawable = (GradientDrawable)layerDrawable.findDrawableByLayerId(R.id.radio_button_selected);
gradientDrawable.setColor(color);
//不可以公用同一个StateListDrawable对象,否则明明不是按下态,却显示的是按下态的图片
StateListDrawable states_on = new StateListDrawable();
StateListDrawable states_off = new StateListDrawable();
states_on.addState(new int[] { android.R.attr.state_selected }, layerDrawable);
states_on.addState(new int[] { -android.R.attr.state_selected }, getDrawable(R.drawable.radio_button_default));
states_off.addState(new int[] { android.R.attr.state_selected }, layerDrawable);
states_off.addState(new int[] { -android.R.attr.state_selected }, getDrawable(R.drawable.radio_button_default));
button_on = (RadioButton)findViewById(R.id.button_on);
button_off = (RadioButton)findViewById(R.id.button_off);
button_on.setBackground(states_on);
button_off.setBackground(states_off);