我想将自定义样式应用于 SwitchCompat。更改打开和关闭状态的绘图和文本。我怎样才能做到这一点?我找不到任何关于如何做到这一点的例子。我在我的 styles.xml 中尝试了以下内容,但显然我没有使用正确的父项:
<style name="Switch" parent="android:Widget.AppCompat.Widget.CompoundButton.SwitchCompat">
<item name="android:textOn">@string/common_yes</item>
<item name="android:textOff">@string/common_no</item>
<item name="android:thumb">@drawable/btn_switch_selector</item>
<item name="android:track">@drawable/btn_switch_bg_selector</item>
</style>
编辑
我设法在代码中更改了可绘制对象。
switchView.setThumbResource(R.drawable.btn_switch_selector);
switchView.setTrackResource(R.drawable.btn_switch_bg_selector);
但我还没有找到改变开关文本的方法。以下代码段似乎不起作用。也许我需要设置更多的文本属性?
switchView.setTextOn(context.getString(R.string.common_yes));
switchView.setTextOff(context.getString(R.string.common_no));
根据 SwitchCompat 源代码,应该支持开/关文本: https ://android.googlesource.com/platform/frameworks/support/+/421d8baa4a524e1384bcf033360bccaf8d55081d/v7/appcompat/src/android/support/v7/widget/ SwitchCompat.java
{@link #setText(CharSequence) text} 属性控制开关标签中显示的文本,而 {@link #setTextOff(CharSequence) off} 和 {@link #setTextOn(CharSequence) on} 文本控制文本在拇指上。
编辑 2
终于找到了代码解决方案。显然setShowText()
需要设置true
为文本才能出现在开关上。
switchView.setTextOn(context.getString(R.string.common_yes));
switchView.setTextOff(context.getString(R.string.common_no));
switchView.setShowText(true);
switchView.setThumbResource(R.drawable.btn_switch_selector);
switchView.setTrackResource(R.drawable.btn_switch_bg_selector);
和xml解决方案
<android.support.v7.widget.SwitchCompat
android:id="@+id/view_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/btn_switch_selector"
app:track="@drawable/btn_switch_bg_selector"
android:textOn="@string/common_yes"
android:textOff="@string/common_no"
app:showText="true" />
我还是想知道有没有办法把它放进去styles.xml
。