- 在 Android 开发中,使用 Switch 控件,Android Studio 报如下警告信息
Use SwitchCompat from AppCompat or SwitchMaterial from Material library
- 在 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" />
- 在 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'
处理策略
- 使用来自 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 ? "开" : "关"));
});
- 来自 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 ? "开" : "关"));
});