我在代码中创建了switch,而不是在xml中。
Switch sw = new Switch(getActivity());
sw.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
sw.setTextOn(getString(R.string.ok));
sw.setTextOff(getString(R.string.remove));
sw.setSwitchMinWidth((int) (4.8 * pixels));
sw.setSwitchTypeface(font);
sw.setThumbResource(R.drawable.thumb);
方法setThumbResource工作正常,但setTrackResource方法导致switch的消失。
我的拇指和轨道的xml文件。它们几乎是一样的。
thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
<solid android:color="#a79d90" />
</shape>
track.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
<solid android:color="#bfb5a7" />
</shape>
另外,我想要做的是为TextOn(绿色)和TextOff(红色)设置不同的颜色。我发现只有一种方法 - setTextColor可以改变两种颜色。
答案 0 :(得分:1)
您好我已经在此链接上发布了答案,这对我有用。
来自那里的代码:
if (isChecked) {
mSwtPrivacyView.getTrackDrawable().setColorFilter(ContextCompat.getColor(this, R.color.switch_track_checked_true_color), PorterDuff.Mode.SRC_IN);
} else {
mSwtPrivacyView.getTrackDrawable().setColorFilter(ContextCompat.getColor(this, R.color.switch_track_checked_false_color), PorterDuff.Mode.SRC_IN);
}
答案 1 :(得分:0)
对于@DjimOnDev。我正在使用这个
Switch sw = new Switch(getActivity());
sw.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
sw.setTextOn(getString(R.string.ok));
sw.setTextOff(getString(R.string.remove));
if (sw.isChecked()) {
sw.setSwitchTextAppearance(getActivity(), R.style.SwitchTextAppearance1);
}
else {
sw.setSwitchTextAppearance(getActivity(), R.style.SwitchTextAppearance2);
}
sw.setSwitchMinWidth((int) (3.6 * pixels));
sw.setThumbResource(R.drawable.thumb);
sw.setTrackResource(R.drawable.track);
sw.setSwitchTypeface(font);
<强> thumb.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#bfb5a7" />
</shape>
<强> track.xml 强>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/thumb_off" />
<item android:drawable="@drawable/thumb_default" />
<强> styles.xml 强>
<style name="SwitchTextAppearance1">
<item name="android:textColor">#5db701</item>
</style>
<style name="SwitchTextAppearance2">
<item name="android:textColor">#ea3d3d</item>
</style>