【问题标题】:Why switch's textOn and textOff are not displaying?为什么不显示 switch 的 textOn 和 textOff?
【发布时间】:2015-06-09 07:49:03
【问题描述】:

我正在尝试使用开/关开关制作列表视图。我找到了这个简单的代码,但问题是它对我不起作用。

<Switch
    android:id="@+id/itemListSwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="Vibrate on"
    android:textOff="Vibrate off"/>

是的,它显示一个开关,但文本(振动开/关)不是。只显示一个可以切换的圆圈。我想发布屏幕截图,但我不被允许,因为我缺乏声誉。谁能告诉我为什么,因为我试图找到答案,但是像上面这样的简单代码对他们有用。如果有帮助,我的 Android 手机版本是 5.0.2。提前致谢!

【问题讨论】:

    标签: android


    【解决方案1】:

    首先您应该使用 SwitchCompat 以使其与所有 android 版本兼容并具有漂亮的开关材料设计外观。

    回到您的问题,您缺少显示文本的属性 -app:showText -,这是一个示例:

    <RelativeLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      ...>
        <android.support.v7.widget.SwitchCompat
            android:id="@+id/switch_compat"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="50dp"
            android:layout_marginStart="50dp"
            android:layout_marginTop="25dp"
            android:checked="false"
            android:textOff="OFF"
            android:textOn="ON"
            app:showText="true"/>
    </RelativeLayout>
    

    【讨论】:

    • 谢谢乔治!这行得通!但不是我所期待的。文字写在圆圈(滑块)内,而不是在它后面,看起来很尴尬。有什么办法可以改变开关的大小和样式吗?还是我必须像其他人一样使用 android:background ?非常感谢您的回答,我希望您对此做出回应!
    • 可以,但是您需要扩展 SwitchCompat 类。看看这里gist.github.com/T-Spoon/fe9f0ee8cbb79049b1ec
    • 嗨,乔治。我尝试通过在不同的 java 文件中创建所述类来使用 SwitchCompatFix,并使用它而不是为我的按钮使用 SwitchCompat 类。我以编程方式创建了一个并将其添加到布局视图中,但 SwitchCompat 的结果仍然相同,文本仍显示在滑块顶部。谢谢并希望您的回复! :)
    【解决方案2】:

    Material 主题下默认不显示文本。

    您可以使用android:showText 属性对其进行更改

    <Switch
        android:id="@+id/itemListSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Vibrate on"
        android:textOff="Vibrate off"
        android:showText="true" />
    

    【讨论】:

    • 成功了!先生非常感谢您!但我现在有一个不同的问题;我期待文本将写在滑块后面。 (因为此刻文字在滑动的小圆圈内),看起来有点尴尬。再次非常感谢您,先生,希望您对此做出回应!
    • 要更改开关样式,请遵循以下答案:stackoverflow.com/a/10140801/1484779
    猜你喜欢
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多