我的应用程序的 Min sdk 是 GingerBread,我遇到了同样的问题,最后我找到了解决方案。为了在所有 android 版本中保持一致,我在文件夹中SwitchCompat
使用了两个可绘制对象,一个用于. 并将它们分配给java代码而不是xml。这是您应该使用的代码。res/drawable
thumb
track
SwitchCompat
SwitchCopmat
小部件:
<android.support.v7.widget.SwitchCompat
android:id="@+id/label_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
拇指可绘制,switch_compat_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="@dimen/switch_compat_thumb_margin"
android:left="@dimen/switch_compat_thumb_margin"
android:right="@dimen/switch_compat_thumb_margin"
android:top="@dimen/switch_compat_thumb_margin">
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape android:shape="oval">
<size
android:width="@dimen/switch_compat_thumb_size"
android:height="@dimen/switch_compat_thumb_size"/>
<solid android:color="@android:color/red"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<size
android:width="@dimen/switch_compat_thumb_size"
android:height="@dimen/switch_compat_thumb_size"/>
<stroke
android:width="@dimen/switch_compat_thumb_stroke_width"
android:color="@android:color/red"/>
<solid android:color="@android:color/transparent" />
</shape>
</item>
</selector>
</item>
可绘制的track
,switch_compat_track.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="@dimen/switch_compat_track_radius"/>
<stroke
android:width="@dimen/switch_compat_track_stroke_width"
android:color="@android:color/red"/>
<solid android:color="@android:color/transparent" />
然后,在java中找到它之后,在java代码中分配thumb
和track
到SwitchCompat
:
final SwitchCopmat switchCompat = (SwitchCopmat) findViewById(R.id.label_switch);
//add thumb and track drawable in java since it doesn't work on xml for gingerbread
switchCompat.setThumbDrawable(getResources().getDrawable(R.drawable.switch_compat_thumb));
switchCompat.setTrackDrawable(getResources().getDrawable(R.drawable.switch_compat_track));