我的应用程序的Min sdk是GingerBread,而且我遇到了同样的问题,最后我找到了解决方案。为了使SwitchCompat
在所有Android版本中保持一致,我使用了两个可绘制文件夹res/drawable
,其中一个用于thumb
,另一个用于track
。并将它们分配给不在xml中的java代码中的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));
的[Switchcompat不显示开关]可能重复(http://stackoverflow.com/问题/ 26563986/switchcompat-not-displays-the-switch) – 2015-04-02 17:17:31
接受的答案是使用'Theme.AppCompat'作为父项,但我仅使用'Theme.AppCompat.NoActionBar'(使用工具栏)。 – user3677365 2015-04-02 17:28:17
如何将9patch和其他文件复制到项目中并使其工作?只有在您的项目没有任何问题时才会这样做。 – 2015-04-03 12:50:41