gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:22:16 25 4
gpt4 key购买 nike

我有两个布局 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com