用Android Studio做安卓开发的时候,使用RadioButton会有系统默认样式,比如:在unchecked状态下是黑色边框+空心圆样式;checked状态下是粉红色边框+中间一个粉红色原点(如下)。
但是有时候我们想要改变前面圆圈的样式,那么怎么修改呢?
可能很多同学网上找到的解决方案,大都是在/drawable下新建一个radio**.xml文件,在<selector>下的<item>下设置当android:state_checked为true/false时,设置android:drawable为/drawable下的不同状态的图片。
那么问题来了,如果我并没有两种状态的图片,比如只是想改一下边框颜色、点击后的颜色这些呢?
其实原理也很简单,而且跟上面的图片替换也很类似,不过上面的是替换/drawable文件夹下的图片,这里介绍的方法是替换/drawable文件夹下的.xml样式文件。步骤如下:
1、先在/drawable文件夹下创建RadioButton状态切换文件,比如radio_button_style.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="true"
android:state_checked="true"
android:drawable="@drawable/radiobtn_checked_style"
/>
<item
android:state_enabled="true"
android:state_checked="false"
android:drawable="@drawable/radiobtn_unchecked_style"
/>
</selector>
<selector>标签下的两个<item>标签分别定义两种状态:checked和unchecked(从上面的state_checked反映)。当被checked时,RadioButton切换到radiobtn_checked_style状态;否则,切换radiobtn_unchecked_style状态。
2、好了,上面两个状态其实是/drawable文件夹下的两个.xml布局文件radiobtn_checked_style.xml和radiobtn_unchecked_style.xml。以下分别是两个布局文件的代码:
radiobtn_checked_style.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:radius="@dimen/pswRadioButtonWidth"/>
<solid
android:color="@color/buttonColorIn"/>
<size
android:height="@dimen/pswRadioButtonWidth"
android:width="@dimen/pswRadioButtonWidth"/>
<stroke
android:width="@dimen/pswRadioButtonStrokeWidth"
android:color="@color/buttonStroke"/>
</shape>
radiobtn_unchecked_style.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:radius="@dimen/pswRadioButtonWidth"/>
<solid
android:color="@color/buttonColor"/>
<size
android:height="@dimen/pswRadioButtonWidth"
android:width="@dimen/pswRadioButtonWidth"/>
<stroke
android:width="@dimen/pswRadioButtonStrokeWidth"
android:color="@color/buttonStroke"/>
</shape>
(1)根标签必须改为<shape>
(2)<size>标签,定义RadioButton的大小(宽高)
(3)<corners>标签,定义原来矩形4个直角的完全程度(与width/heigth一致则为圆角)
(4)<solid>为中间填充颜色
(5)<stroke>为边框属性
(当然shape还有一些其他属性,在这里没用上就没写出来)
3、好了,定义好布局,最后在整体布局的RadioButton下把状态切换文件radio_button_style.xml加到android:button属性下即可。比如:
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/pswRadioBtn1"
android:layout_marginTop="20dp"
android:checked="false"
android:layout_below="@+id/hintText"
android:layout_alignEnd="@+id/button1"
android:clickable="false"
android:button="@drawable/radio_button_style" />
4、最后展示一下我写的RadioButton,在没有添加切换图片下的自定义效果:
unchecked:
checked:
很像iOS的效果是不是!!