一、应用场景:
在使用 RadioButton 时,有时我们会需要自定义点击时改变背景颜色的效果。
效果图:
RadioButton自定义背景颜色.jpg二、实现步骤:
1、新建一组 RadioButton :
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="@+id/btn1"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:background="@drawable/radiobutton_background"
android:button="@null"
android:gravity="center"
android:text="P0501"
android:textColor="@color/radiobutton_textcolor"
android:textSize="14sp" />
<RadioButton
android:id="@+id/btn2"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_marginStart="10dp"
android:layout_weight="1"
android:background="@drawable/radiobutton_background"
android:button="@null"
android:gravity="center"
android:text="P0502"
android:textColor="@color/radiobutton_textcolor"
android:textSize="14sp" />
<RadioButton
android:id="@+id/btn3"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_marginStart="10dp"
android:layout_weight="1"
android:background="@drawable/radiobutton_background"
android:button="@null"
android:gravity="center"
android:text="P0503"
android:textColor="@color/radiobutton_textcolor"
android:textSize="14sp" />
</RadioGroup>
注意:这里有2个关键属性,说明一下
1)、android:button="@null" 这样设置可以不显示我们通常所见的 RadioButton 中的圆形选中按钮.
2)、android:background="@drawable/radiobutton_background" 这里设置了背景选择器。
2、radiobutton_background.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/radiobutton_background_unchecked"
android:state_checked="false" />
<item android:drawable="@drawable/radiobutton_background_checked"
android:state_checked="true" />
</selector>
3、radiobutton_background_checked.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充 -->
<solid android:color="@color/color1" />
<!-- 圆角 -->
<corners android:radius="5dp" />
</shape>
4、radiobutton_background_unchecked.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充 -->
<solid android:color="@color/color2" />
<!-- 圆角 -->
<corners android:radius="5dp" />
</shape>
5、RadioGroup 的单选监听器,获取选中的RadioButton
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
String result = radioButton.getText().toString();
}
});
网友评论