use*_*365 4 android android-layout android-switch
我试图从AppCompat实现SwitchCompat,但它在不同的版本设备上看起来不同.在棒棒糖和Froyo它看起来不错,但在姜饼到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" />
Run Code Online (Sandbox Code Playgroud)
我是否可以使这些开关在所有版本中看起来相同或者至少使它们看起来像一个开关?
She*_*rry 11
我应用程序的最小sdk是GingerBread,我有同样的问题,最后我找到了解决方案.为了SwitchCompat在所有Android版本中保持一致,我在res/drawable文件夹中使用了两个drawable ,一个用于thumb和一个用于track.并将它们分配给SwitchCompat不在xml中的java代码.这是您应该使用的代码.
SwitchCopmat 小工具:
<android.support.v7.widget.SwitchCompat
android:id="@+id/label_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Run Code Online (Sandbox Code Playgroud)
drawable for thumb,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>
Run Code Online (Sandbox Code Playgroud)
drawable for 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" />
Run Code Online (Sandbox Code Playgroud)
然后,在java中发现它后,分配thumb和track对SwitchCompatJava代码:
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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4422 次 |
| 最近记录: |