Android 在预棒棒糖设备上使用SwitchCompat
我正在尝试从AppCompat实现SwitchCompat,但它在不同版本的设备上看起来有所不同。 在棒棒糖和Froyo上看起来不错,但在姜饼和KitKat上看起来不像是一个开关 代码:Android 在预棒棒糖设备上使用SwitchCompat,android,android-layout,android-switch,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
<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" />
我能让这些开关在所有版本中看起来都一样吗,或者至少让它们看起来像一个开关吗?我的应用程序的Min sdk是姜饼,我遇到了同样的问题,最后我找到了解决方案。为了使
SwitchCompat
在所有android版本中保持一致,我在res/drawable
文件夹中使用了两个drawable,一个用于thumb
,另一个用于track
。并将它们分配给java代码中而不是xml中的SwitchCompat
。下面是您应该使用的代码
SwitchCopmat
小部件:
<android.support.v7.widget.SwitchCompat
android:id="@+id/label_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
然后,在java中找到它后,将thumb
和track
分配给java代码中的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));
可能重复的已接受答案是使用
Theme.AppCompat
作为父级,但我只使用Theme.AppCompat.NoActionBar
(使用工具栏)。将9patch和其他文件复制到项目中并使其工作如何?只有在你的项目没有任何问题的情况下才能这样做。是的,我在可绘制的hdpi中添加了它们(2个缺少9个补丁png),但不起作用。这是因为我在3.4英寸屏幕的模拟器中进行了测试吗?复制图像后,我是否需要指定一些内容?这几乎适用于我,但您可以包含来自dimens的定义吗?边缘、宽度等。Thanks@shtolik在switch_compat_thumb.xml中,项目(按钮、左、上、右)有4dp,然后第一个椭圆形有8dp(宽度和高度),strock有4dp宽度。第二个椭圆形的宽度和高度为8dp,笔划宽度为2dp。在switch_compat_track.xml中,矩形具有半径为7dp的角和宽度为2dp的笔划
<?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" />
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));