我在 android 中实现了一个自定义开关(如 iOS)。它在 xhdpi 设备(Nexus 4、moto g3)中运行良好。但不能减少 Nexus S 中 switch 的轨道宽度。它太长了。
custom_switch_thumb
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="true">
<shape
android:shape="rectangle"
android:visible="true"
android:dither="true"
android:useLevel="false">
<gradient
android:startColor="#66AAFF00"
android:endColor="#6600FF00"
android:angle="270"/>
<corners
android:radius="20dp"/>
<size
android:width="30dp"
android:height="30dp" />
<stroke
android:width="4dp"
android:color="#0000ffff"/>
</shape>
</item>
<item android:state_checked="false">
<shape
android:shape="rectangle"
android:visible="true"
android:dither="true"
android:useLevel="false">
<gradient
android:startColor="#ff0000"
android:endColor="#ff0000"
android:angle="270"/>
<corners
android:radius="20dp"/>
<size
android:width="30dp"
android:height="30dp" />
<stroke
android:width="4dp"
android:color="#0000ffff"/>
</shape>
</item>
custom_switch_track
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:visible="true"
android:dither="true"
android:useLevel="false">
<gradient
android:startColor="#27170432"
android:endColor="#27170432"
android:angle="270"/>
<corners
android:radius="20dp"/>
<size
android:width="60dp"
android:height="30dp" />
</shape>
开关放置在布局中
<Switch
android:id="@+id/notification_client_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="8dp"
android:gravity="center"
android:showText="true"
android:switchMinWidth="0dp"
android:switchTextAppearance="@style/SwitchTextAppearance"
android:textOff="@string/no_label"
android:textOn="@string/yes_label"
android:thumb="@drawable/custom_switch_selector"
android:track="@drawable/custom_switch_track" />
我已经更改了轨道宽度并使用不同的值切换“android:switchminwidth”,但没有发现任何效果。