如何使用带有xamarin单选按钮的选择器来设置背景颜色?

时间:2014-07-08 00:35:07

标签: button xamarin selector radio

我有两个单选按钮,看起来像普通按钮。我想通过使用带有选择器的radio_button.xml来改变它们的背景颜色。 如果我使用小的.png图像来设置背景,那么它工作正常。 但我尝试使用类似的代码只使用颜色(整数),但它不起作用。我做错了什么?

带背景图片的代码:

<RadioGroup
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <RadioButton
        android:text="LEFT"
        android:id="@+id/radioLeft"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:background="@drawable/radio_button"
        android:checked="true" />
    <RadioButton
        android:text="RIGHT"
        android:id="@+id/radioRight"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:background="@drawable/radio_button" />
</RadioGroup>

radio_button.xml

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

button_colors.xml

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <color name="button_black">#000000</color>
  <color name="button_white">#ffffff</color>
  <color name="button_blue">#00afdb</color>
  <color name="button_gray">#dcdcdc</color>
</resources>

我试图替换

android:drawable="@drawable/blue_dot"

android:background="@color/button_blue"

但它没有用。怎么解决?

1 个答案:

答案 0 :(得分:0)

我使用带有颜色的形状xml来避免背景图像。

radio_button.xml

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

rb_checked.xml

<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
       android:shape="rectangle" >
  <solid android:color="@color/button_blue" />
</shape>

Main.axml

<RadioGroup
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <RadioButton
        android:checked="true"
        android:text="LEFT"
        android:id="@+id/radioLeft"
        android:button="@android:color/transparent"
        android:background="@drawable/radio_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" />
    <RadioButton
        android:text="RIGHT"
        android:id="@+id/radioRight"
        android:button="@android:color/transparent"
        android:background="@drawable/radio_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" />
</RadioGroup>

Buttons in the cell phone emulator: