我有两种布局,一种用于 API 级别 14 之前,另一种用于之后。我需要在 14 级 API 之前使用切换按钮,在 14 级之后使用切换按钮。
问题是我想在 R.id.button1 中使用具有相同 ID 的两者,或者我是否必须使每个具有不同的 ID 并在 Java 代码中检查运行的 API 版本,以便找到 View 通过适用于 API 的 ID。如果是这样,我该怎么做,请提供代码示例。 感谢您的宝贵时间。
这些是 XML 文件
layout-v14:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Switch
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_alignParentRight="true"
android:layout_marginRight="16dp" />
</RelativeLayout>
普通布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ToggleButton
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_alignParentRight="true"
android:layout_marginRight="16dp" />
</RelativeLayout>
Java代码
CompoundButton button = (CompoundButton) findViewById(R.id.button1);
最佳答案
它们都扩展了 CompoundButton,因此您可以使用相同的 ID,但是如果您想要相同的代码,则必须将您的使用限制在 CompoundButton 类。
编辑
CompoundButton button = (CompoundButton) findViewById(R.id.button1);
button.setChecked(checked);
关于android - 如何使布局适应多 Android API 级别以使用开关和切换按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14748093/