Android Studio 中 Switch 控件警告信息:Use SwitchCompat from AppCompat or SwitchMaterial from Material...

  • 在 Android 开发中,使用 Switch 控件,Android Studio 报如下警告信息
Use SwitchCompat from AppCompat or SwitchMaterial from Material library
  1. 在 XML 文件中会有这个警告信息
<Switch
    android:id="@+id/sw_test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
  1. 在 Java 代码中也会有这个警告信息
private Switch swTest;
问题描述
  • 这个警告信息是 Android Studio 建议开发者使用 SwitchCompat 控件或 SwitchMaterial 控件替代标准的 Switch 控件

  • 来自 AppCompat 库的 SwitchCompat 和来自 Material Design 库 SwitchMaterial 提供了更好的兼容性和 Material Design 风格

// AppCompat 库
implementation 'androidx.appcompat:appcompat:1.3.0'

// Material Design 库
implementation 'com.google.android.material:material:1.4.0'
处理策略
  1. 使用来自 AppCompat 库的 SwitchCompat
<androidx.appcompat.widget.SwitchCompat
    android:id="@+id/swc_test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
private SwitchCompat swcTest;

...

swcTest = findViewById(R.id.swc_test);

swcTest.setOnCheckedChangeListener((buttonView, isChecked) -> {
    Log.i(TAG, "SwitchCompat 按钮的状态是:" + (isChecked ? "开" : "关"));
});
  1. 来自 Material Design 库 SwitchMaterial
<com.google.android.material.switchmaterial.SwitchMaterial
    android:id="@+id/swm_test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
private SwitchMaterial swmTest;

...

swmTest = findViewById(R.id.swm_test);

swmTest.setOnCheckedChangeListener((buttonView, isChecked) -> {
    Log.i(TAG, "SwitchMaterial 按钮的状态是:" + (isChecked ? "开" : "关"));
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值