5

我正在尝试从 AppCompat 实现 SwitchCompat,但它在不同版本的设备上看起来不同。在 Lollipop & Froyo 上它看起来不错,但在 Gingerbread 到 KitKat 上它看起来不像是一个开关。

代码:

<android.support.v7.widget.SwitchCompat
        android:id="@+id/label_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="No"
        android:textOn="Yes"
        android:checked="false" />

我可以让这些开关在所有版本中看起来都一样,或者至少让它们看起来像一个开关吗?

4

1 回答 1

12

我的应用程序的 Min sdk 是 GingerBread,我遇到了同样的问题,最后我找到了解决方案。为了在所有 android 版本中保持一致,我在文件夹中SwitchCompat使用了两个可绘制对象,一个用于. 并将它们分配给java代码而不是xml。这是您应该使用的代码。res/drawablethumbtrackSwitchCompat

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代码中分配thumbtrackSwitchCompat

  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));
于 2015-06-28T22:49:21.147 回答