我在自定义 Android Switch 小部件的外观时遇到问题。我有一些自定义的xml可绘制对象,我想将它们用于拇指(通常表示“打开”或“关闭”的小按钮部分)和轨道(拇指滑过的背景)。当我只使用 android:thumb 设置拇指时,它工作正常。当我设置轨道时(无论是否设置拇指),开关完全消失,只剩下文本显示。

这是仅应用拇指时的代码:

<com.blahblahblah.blah.CustomSwitch
    android:id="@+id/switch_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOff="Off"
    android:textOn="On"
    android:text="Something Awesome"
    android:textColor="@android:color/black"
    android:thumb="@drawable/custom_switch_thumb" />

这是预览窗口中的样子:

并应用轨道:
<com.blahblahblah.blah.CustomSwitch
    android:id="@+id/switch_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOff="Off"
    android:textOn="On"
    android:text="Something Awesome"
    android:textColor="@android:color/black"
    android:track="@color/track_color" />

应用轨道的预览窗口:

作为引用,我在 OSX 10.7.5 上使用 Android Studio 0.2.3。

最佳答案

我只是偶然发现了同样的问题,并通过HoloEverywhere issue tracker找到了解决方法。您需要设置所使用的可绘制XML形状的<size>

无法正常工作(小部件在那里,我可以与它进行交互,但是我看不到它,它是隐藏的):

<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">

  <solid android:color="@color/black_50" />
</shape>

工作(不是添加的<size>):
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">

  <solid android:color="@color/black_50" />
  <size android:width="56dp" android:height="20dp" />
</shape>

09-30 17:41
查看更多