我有两个布局xml文件,在Main.xml中,有一个名为android:id =“ @ + id / btnClose”的按钮,在About.xml中也有一个名为android:id =“ @ + id / btnClose的按钮”,
可以吗谢谢!

Main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="3dip"
    android:layout_marginTop="3dip"
    android:background="#DCDCDC" >

     <Button
        android:id="@+id/btnClose"
        style="@style/myTextAppearance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="@string/exit" />
</RelativeLayout>


About.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingTop="3dip"
    android:paddingLeft="7dip"
    android:background="@drawable/border_ui"
    android:orientation="vertical" >

     <Button
        android:id="@+id/btnClose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        style="@style/myTextAppearance"
        android:text="@string/myreturn" />


</LinearLayout>

最佳答案

可以相同。

但是为了避免混淆/模棱两可,最好使用blackbelt建议的其他ID。

您可以将当前视图层次结构的findViewById设置为活动。因此,如果您在不同的xml布局中具有相同的ID,就可以了。

如果您有以下内容

setContentView(R.layout.main)
Button b = (Button) findViewById(R.id.btnClose); // initialize button


您可以找到当前视图层次结构的ViewById。在你的情况下main.xml

如果您有以下内容

setContentView(R.layout.about);
Button b = (Button) findViewById(R.id.btnClose); // initialize button


以上两种情况均有效,因为main.xmlabout.xml都具有ID为@+id/btncClose的按钮

假设您在@+id/button2中具有ID为about.xml的第二个按钮,并且具有以下内容

 setContentView(R.layout.main);
 Button b = (Button) findViewById(R.id.button2);


您将得到NullPointerException,因为设置为活动的当前视图层次结构是main.xml而不是about.xmlmain.xml没有ID为button2的按钮。

10-08 06:45
查看更多