用Android Studio做安卓开发的时候,使用RadioButton会有系统默认样式,比如:在unchecked状态下是黑色边框+空心圆样式;checked状态下是粉红色边框+中间一个粉红色原点(如下)。
但是有时候我们想要改变前面圆圈的样式,那么怎么修改呢?
可能很多同学网上找到的解决方案,大都是在/drawable下新建一个radio**.xml文件,在
那么问题来了,如果我并没有两种状态的图片,比如只是想改一下边框颜色、点击后的颜色这些呢?
其实原理也很简单,而且跟上面的图片替换也很类似,不过上面的是替换/drawable文件夹下的图片,这里介绍的方法是替换/drawable文件夹下的.xml样式文件。步骤如下:
1、先在/drawable文件夹下创建RadioButton状态切换文件,比如radio_button_style.xml
android:state_enabled="true"
android:state_checked="true"
android:drawable="@drawable/radiobtn_checked_style"
/>
android:state_enabled="true"
android:state_checked="false"
android:drawable="@drawable/radiobtn_unchecked_style"
/>
2、好了,上面两个状态其实是/drawable文件夹下的两个.xml布局文件radiobtn_checked_style.xml和radiobtn_unchecked_style.xml。以下分别是两个布局文件的代码:
radiobtn_checked_style.xml:
android:radius="@dimen/pswRadioButtonWidth"/>
android:color="@color/buttonColorIn"/>
android:height="@dimen/pswRadioButtonWidth"
android:width="@dimen/pswRadioButtonWidth"/>
android:width="@dimen/pswRadioButtonStrokeWidth"
android:color="@color/buttonStroke"/>
radiobtn_unchecked_style.xml
android:radius="@dimen/pswRadioButtonWidth"/>
android:color="@color/buttonColor"/>
android:height="@dimen/pswRadioButtonWidth"
android:width="@dimen/pswRadioButtonWidth"/>
android:width="@dimen/pswRadioButtonStrokeWidth"
android:color="@color/buttonStroke"/>
(1)根标签必须改为
(2)
(3)
(4)
(5)
(当然shape还有一些其他属性,在这里没用上就没写出来)
3、好了,定义好布局,最后在整体布局的RadioButton下把状态切换文件radio_button_style.xml加到android:button属性下即可。比如:
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:
位置改变
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:button="@null"
android:drawableRight="@drawable/round_checkbox_style"
android:text="离线"/>
代码设置
Drawable drawable = getResources().getDrawable(R.drawable.img);
drawable.setBounds(0, 0, 32, 32);
textView.setCompoundDrawables(drawable, null, null, null);