一、警告代码
<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: 链接。
本文介绍了在Android开发中遇到的警告,即使用旧版Switch控件可能导致外观不一致的问题。为了解决这个问题,文章提出了两种解决方案:SwitchCompat和SwitchMaterial。SwitchCompat适用于所有Android版本,提供一致的外观;而SwitchMaterial是Material Design风格的开关,需设置特定主题颜色。同时提供了相关API链接供开发者参考。
5073

被折叠的 条评论
为什么被折叠?



