RadioButton设置自定义选中

用Android Studio做安卓开发的时候,使用RadioButton会有系统默认样式,比如:在unchecked状态下是黑色边框+空心圆样式;checked状态下是粉红色边框+中间一个粉红色原点(如下)。

  

 

但是有时候我们想要改变前面圆圈的样式,那么怎么修改呢?

可能很多同学网上找到的解决方案,大都是在/drawable下新建一个radio**.xml文件,在下的下设置当android:state_checked为true/false时,设置android:drawable为/drawable下的不同状态的图片。

那么问题来了,如果我并没有两种状态的图片,比如只是想改一下边框颜色、点击后的颜色这些呢?

 

其实原理也很简单,而且跟上面的图片替换也很类似,不过上面的是替换/drawable文件夹下的图片,这里介绍的方法是替换/drawable文件夹下的.xml样式文件。步骤如下:

 

1、先在/drawable文件夹下创建RadioButton状态切换文件,比如radio_button_style.xml

 

 
  1. android:state_enabled="true"

  2. android:state_checked="true"

  3. android:drawable="@drawable/radiobtn_checked_style"

  4. />

  5.  
  6. android:state_enabled="true"

  7. android:state_checked="false"

  8. android:drawable="@drawable/radiobtn_unchecked_style"

  9. />

  10.  

    标签下的两个标签分别定义两种状态: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:

 

 
  1. android:radius="@dimen/pswRadioButtonWidth"/>

  2.  
  3. android:color="@color/buttonColorIn"/>

  4.  
  5. android:height="@dimen/pswRadioButtonWidth"

  6. android:width="@dimen/pswRadioButtonWidth"/>

  7.  
  8. android:width="@dimen/pswRadioButtonStrokeWidth"

  9. android:color="@color/buttonStroke"/>

  10.  
  11.  

 

 

radiobtn_unchecked_style.xml

 

 
  1. android:radius="@dimen/pswRadioButtonWidth"/>

  2.  
  3. android:color="@color/buttonColor"/>

  4.  
  5. android:height="@dimen/pswRadioButtonWidth"

  6. android:width="@dimen/pswRadioButtonWidth"/>

  7.  
  8. android:width="@dimen/pswRadioButtonStrokeWidth"

  9. android:color="@color/buttonStroke"/>

  10.  

 (1)根标签必须改为

 

    (2)标签,定义RadioButton的大小(宽高)

    (3)标签,定义原来矩形4个直角的完全程度(与width/heigth一致则为圆角)

    (4)为中间填充颜色

    (5)为边框属性

    (当然shape还有一些其他属性,在这里没用上就没写出来)
 

3、好了,定义好布局,最后在整体布局的RadioButton下把状态切换文件radio_button_style.xml加到android:button属性下即可。比如:

 

 
  1. android:layout_width="wrap_content"

  2. android:layout_height="wrap_content"

  3. android:id="@+id/pswRadioBtn1"

  4. android:layout_marginTop="20dp"

  5. android:checked="false"

  6. android:layout_below="@+id/hintText"

  7. android:layout_alignEnd="@+id/button1"

  8. android:clickable="false"

  9. 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);

你可能感兴趣的:(RadioButton设置自定义选中)