警告:使用 AppCompat 中的 SwitchCompat 或材料库中的 SwitchMaterial

Den*_*nis 19 android lint android-appcompat android-switch material-components-android

这两个对象(SwitchCompatSwitchMaterial)之间有什么区别?我已经尝试过它们并且在视觉上它们是相同的。

顺便问一下,他们为什么要删除这个Switch类?您知道将来应该用哪个 UI 元素来替换它吗?

Gab*_*tti 12

SwitchMaterial

  • 材料组件库提供
  • 延长 SwitchCompat
  • 用途Widget.MaterialComponents.CompoundButton.Switch作为默认的样式,使用颜色在所定义Theme.MaterialComponents(如colorSecondarycolorSurfacecolorOnSurface),并施加高度叠加在暗模式。

SwitchCompat

顺便说一句,他们为什么要删除 Switch 类?

Switch类不会被删除。它像其他小部件一样由 android 框架提供ButtonTextView..,而 appcompat 和 material 组件库提供它们的更新版本(例如AppCompatButton,.. MaterialButton)。

这些小部件有所不同。使用AppCompat主题AppCompatViewInflater可以自动替换从布局文件膨胀的核心 Android 小部件的所有用法,这些小部件的 AppCompat 扩展名(例如 aButton被替换为AppCompatButton)。
如果Theme.MaterialComponents 正在使用MaterialComponentsViewInflaterMaterial Components 主题(例如 aButton被替换为MaterialButton),则使用 可以在膨胀时用 Material Components 替换一些框架小部件。

对于和 而言,情况并非如此。其原因是由于 AppCompat实际上并未从框架类扩展而来。SwitchMaterialSwitchCompatSwitchCompatSwitch

  • 是的,但是他们为什么要做出这样的改变呢?为什么我们不能像以前一样继续使用 Switch?SwitchMaterial 和 SwitchCompat 有何作用使其值得转换? (13认同)

Ang*_*Koh 8

https://developer.android.com/reference/androidx/appcompat/widget/SwitchCompat

Switch 对于旧版本的 Android 有不同的外观。我们使用 SwitchCompat 为所有 Android 版本提供一致的外观。

在此处输入图片说明

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

SwitchMaterial 继承自 SwitchCompat。它是一个创建材质主题开关的类。


Yil*_*maz 5

根据您使用的 Android 版本,切换视图的操作方式有所不同。如果您的应用程序在旧版本或新版本中运行,这可能会导致问题。为了解决这个问题,我们可以使用SwitchCompat当前所有版本都具有相同操作的方法。

要调整这一点,请转到 xml 代码,而不是 switch

// change from "Switch"
<androidx.appcompat.widget.SwitchCompat
        android:id="@+id/main_activity_sw_simulate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="9dp"
        android:fontFamily="@font/coda"
        android:text="@string/switch_text"
        android:textColor="@color/onyx"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="TouchTargetSizeCheck" />
Run Code Online (Sandbox Code Playgroud)