Android SwitchCompat style

£可爱£侵袭症+ 提交于 2019-12-02 08:17:12

问题


I tested my app on my new device with android 5.1.1. In my SettingsActivity i have a switch. I already read some posts and changed it to android.support.v7.widget.SwitchCompat but the problem still is the following: On my old device the switch looks very nice. you can set two texts for textOn and textOff and it fits perfectly. but since api 21 or whatever I get this little bastard here:

It looks like ****. How can I restyle it for all devices like the lollypop switch?

Edit: The question above is answered. One tiny thing is missing: How to change the color of the text on the switch.(Not the tag on the left side!!!)

styles.xml

<style name="SwitchTextAppearance" parent="TextAppearance.AppCompat.Widget.Switch">
        <item name="android:textSize">12sp</item>
        <item name="android:textColor">#3F51B5</item>
    </style>

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingBottom="12dp"
    android:paddingTop="12dp">

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/mySwitch"
        android:layout_width="match_parent"
        android:switchMinWidth="56dp"
        android:layout_height="wrap_content"
        android:switchTextAppearance="@style/SwitchTextAppearance"
        android:thumb="@drawable/thumb"
        android:track="@drawable/track"
        app:showText="true"
        android:textOn="ON"
        android:textOff="OFF"
        android:text="Toggle Switch"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:background="@android:color/transparent"
        android:button="@null"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"/>

</RelativeLayout>

回答1:


Using SwitchCompat.setSwitchTextAppearance you can set the style for the text that appears inside the switch itself.

Add a style something like this and set it using setSwitchTextAppearance:

<style name="SwitchTextAppearance" parent="TextAppearance.AppCompat.Widget.Switch">
  <item name="android:textSize">12sp</item>
  <item name="android:textColor">#3F51B5</item>
</style>

And you should be able to customize the size, color, etc of your "OFF" text.



来源:https://stackoverflow.com/questions/36314877/android-switchcompat-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!