无法在android中更改单选按钮圆圈颜色

时间:2017-09-04 04:40:33

标签: android colors radio-button

我在我的应用中使用radioButton但默认情况下我的radioButton颜色是黑色的,当我选择它时会变成我在color.xml中提到的颜色强调颜色但是我想要将radioButton初始颜色和所选颜色更改为白色。我怎么能这样做。我尝试了背景颜色,但它改变了背景颜色属性。请帮忙。

1 个答案:

答案 0 :(得分:1)

首先将此代码放在style.xml

<!-- custom style -->
<style name="radionbutton"
       parent="Base.Widget.AppCompat.CompoundButton.RadioButton">
    <item name="android:button">@drawable/rb_drawable</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">false</item>
    <item name="android:backgroundDimEnabled">true</item>
</style>

现在在可绘制文件夹中创建rb_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/radio_unchecked" android:state_checked="false" android:state_focused="true"/>
  <item android:drawable="@drawable/radio_unchecked" android:state_checked="false" android:state_focused="false"/>
  <item android:drawable="@drawable/radio_checked" android:state_checked="true" android:state_focused="true"/>
  <item android:drawable="@drawable/radio_checked" android:state_checked="true" android:state_focused="false"/>
</selector> 

现在为可绘制文件夹中的单选按钮选中/取消选中另外两个文件

<强> radio_unchecked.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="oval">
  <stroke android:width="1dp" android:color="@color/colorAccent"/>
  <size android:width="30dp" android:height="30dp"/>
</shape>

<强> radio_checked.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="oval">
      <stroke android:width="1dp" android:color="@color/colorAccent"/>
      <size android:width="30dp" android:height="30dp"/>
    </shape>
  </item>
  <item android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp">
    <shape android:shape="oval">
      <solid android:width="1dp" android:color="@color/colorAccent"/>
      <size android:width="10dp" android:height="10dp"/>
    </shape>
  </item>
</layer-list>

最后在布局xml中更改单选按钮的样式

<RadioButton
    android:layout_width="wrap_content"
    style="@style/radionbutton"
    android:checked="false"
    android:layout_height="wrap_content"
    />