android - 如何使布局适应多 Android API 级别以使用开关和切换按钮?

标签 android android-layout

我有两种布局,一种用于 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/

相关文章:

android - 将 FrameLayout 分配为父 RelativeLayout 的一半

java - 带有固定选项卡的操作栏

android - 使用 Maven 为不同环境(开发、暂存、生产)构建应用程序

android - 使用 Volley 库缓存文本和图像

android - react native : Emulator stuck on "loading from localhost:8081.."

android - 处理程序和可运行泄漏

单个自定义 View 中的 Android 两个 Canvas (在 onDraw() 中)

Android - setVisibility 导致 java.util.ConcurrentModificationException

java - Android RecyclerView 内的relativelayout 无法正确滚动

java - NullPointerException onCreate - android spinner