android - 不同layout xml中的id一定不一样吧?

标签 android

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

主.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。

您可以将当前 View 层次结构的findViewById 设置为 Activity 。因此,如果您在不同的 xml 布局中有相同的 ID,那也没关系。

如果你有以下情况

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

可以找到当前 View 层级的ViewById。在你的情况下 main.xml

如果你有以下

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

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

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

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

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

关于android - 不同layout xml中的id一定不一样吧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17251214/

相关文章:

android - 在 Android 应用程序中通过 VideoView 将正在播放的视频静音

android - 如何在软键盘 Android 的前面显示我的布局?

android - 错误 :(6, 0) 未找到 Gradle DSL 方法: 'google()'

android - 记录 HLS block 请求

android - vkontakte 在 android 中的墙上共享消息?

java - java中如何拆分字符串

android - 如何确定 Android 设备的 GPS 是否已启用

android - 我的 .xml 布局文件的图形表示为空白

java - 字符串空测试中的错误值 (java x kotlin)

android - 增加 CheckboxPreference 标题和摘要文本大小以及首选项条目的发光