Android Switch控件警告:Use SwitchCompat from AppCompat or SwitchMaterial from Material library

一、警告代码

<Switch
	android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

二、警告内容

原文: Use SwitchCompat from AppCompat or SwitchMaterial from Material library.

翻译: 使用AppCompat中的 SwitchCompat 或 Material 库中 SwitchMaterial。

三、原因描述

因为 Switch 对于旧版本的 Android 有不同的外观。则使用 SwitchCompat 可以为所有 Android 版本提供一致的外观。

在这里插入图片描述

四、解决方案

1、SwitchCompat

<androidx.appcompat.widget.SwitchCompat
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"/>

SwitchCompat 是核心 Switch 控件的完整向后移植版,它将该控件的视觉效果和功能带到了旧版本的平台。与此包中的其他控件不同,SwitchCompat 不会自动用于使用该元素的布局中。相反,您需要在布局中显式使用 <androidx.appcompat.widget.SwitchCompat> 和匹配的属性。

2、SwitchMaterial

 <com.google.android.material.switchmaterial.SwitchMaterial
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"/>

它是一个创建 Material主题 Switch 的类,继承自 SwitchCompat。
此类使用来自 Material Theme 的属性来设置 Switch 的样式。除了颜色变化外,它的行为与 相同 SwitchCompat 。必须设置您的主题的 ?attr/colorControlActivated?attr/colorSurface?attr/colorOnSurface 。由于 SwitchCompat 不扩展 Switch,您必须 SwitchMaterial 在布局 XML 中显式声明。

五、链接

1、SwitchCompat 官方API: 链接

2、SwitchMaterial 官方API: 链接

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
要更改 Android SwitchCompat 组件的字体颜色,您可以使用以下代码: ```xml <android.support.v7.widget.SwitchCompat android:id="@+id/switchButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Switch" android:textColor="@color/switch_text_color" android:thumbTint="@color/switch_thumb_color" android:trackTint="@color/switch_track_color" /> ``` 其中,`android:textColor` 属性可以更改文本颜色;`android:thumbTint` 属性可以更改滑块的颜色;`android:trackTint` 属性可以更改轨道的颜色。 您需要在您的资源文件夹中创建一个颜色文件,并在其中定义颜色值,例如: ```xml <resources> <color name="switch_text_color">#FFFFFF</color> <color name="switch_thumb_color">#FF4081</color> <color name="switch_track_color">#BDBDBD</color> </resources> ``` 这将更改 SwitchCompat 组件的文本颜色为白色,滑块颜色为粉色,轨道颜色为灰色。 如果您想要更改 SwitchCompat 组件的填充和大小,您可以使用以下代码: ```xml <android.support.v7.widget.SwitchCompat android:id="@+id/switchButton" android:layout_width="64dp" android:layout_height="32dp" android:text="Switch" android:textColor="@color/switch_text_color" android:thumbTint="@color/switch_thumb_color" android:trackTint="@color/switch_track_color" android:thumbTextPadding="8dp" /> ``` 在这个例子中,我们将 SwitchCompat 组件的宽度设置为 64dp,高度设置为 32dp,并将 `android:thumbTextPadding` 属性设置为 8dp,以增加滑块的大小。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Android Hai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值