为交换机设置样式如何设置正确的图像

时间:2015-03-03 11:04:10

标签: android

我有两个图形:

enter image description here

enter image description here

第一个图形应该是开关的背景,但是当我设置它时:

android:background="@drawable/custom_background"

未设置图像。根本没有背景。 我可以使用以下方法成功设置第二个图形:

android:thumb="@drawable/custom_switch_thumb"

如何设置开关的背景?

1 个答案:

答案 0 :(得分:1)

使用android:track="@drawable/custom_background"

如果要为自定义开关添加颜色,还可以使用trackthumb的选择器,然后在选择器中使用彩色图像。这样您就可以向用户提供当前开关状态的一些视觉反馈

<强>更新

在drawable文件夹中,创建一个名为switch_bg.xml的文件,其中包含以下内容。 switch_bg_onswitch_bg_off是用于曲目的图像。利用你想要的颜色来打开和关闭状态。

<?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/switch_bg_on" />
  <item                               android:drawable="@drawable/switch_bg_off" />
</selector>

然后在drawable文件夹中创建一个文件switch_thumb.xmlswitch_thumb_onswitch_thumb_off再次成为图片。

<?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/switch_thumb_on" />
  <item                               android:drawable="@drawable/switch_thumb_off" />
</selector>

然后在您的交换机视图中使用以下内容:

<Switch 
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:track="@drawable/switch_bg"
   android:thumb="@drawable/switch_thumb" />