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: 链接

本文转自 https://blog.csdn.net/notthin/article/details/121903846,如有侵权,请联系删除。

posted @ 2022-06-16 09:57  yassine  阅读(544)  评论(0编辑  收藏  举报