我有两种布局,一种用于API级别14之前的布局,另一种用于之后的布局。我需要在14级API之前使用切换按钮,在14级API之后使用一个切换按钮。

问题是我想在R.id.button1中使用两个具有相同ID的标识符,还是我必须使每个ID都具有不同的ID,并在Java代码中检查正在运行的API版本,所以我通过ID查找视图适用于API。如果是这样,我该怎么做,请提供代码示例。谢谢你的时间。

这些是XML文件

布局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);

07-27 19:39