我们都知道使用
为Android生成ID时@+id/foo
Android为我们创建了R.java中的条目,如:
public static final class id {
public static final int foo=0x7f060005;
}
如果在不同的xml文件中存在名称冲突会发生什么(比方说,在两个布局中)? @ + id机制确保我们覆盖id名称,如果另一个仍然存在,但是在R.java中为我们生成了哪一个?
答案 0 :(得分:25)
如果id不存在或使用现有ID,@+id/foo
语法将添加
当您找到ViewById时,它将在您调用该方法的视图上运行。
因此,如果您有嵌套的视图,那么您的ID对于每个视图都是唯一的。
例如View1 - > View2都有foo。
View1.findViewById(R.id.foo)
与View2.findViewById(R.id.foo)
编辑:我想主要提到的是两个布局不能具有相同的ID。 有关id约束的更多信息:http://d.android.com/guide/topics/ui/declaring-layout.html
答案 1 :(得分:4)
我使用以下xml尝试了一个简单的Hello World应用程序:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="text1"
/>
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="text2"
/>
</LinearLayout>
我的文字视图都具有相同的ID。它编译得很好,运行正常,渲染两个TextViews,当我执行findViewByid()时,第一个找到它,并且我的所有函数调用如setText都应用于它。理想情况下,AAPT应该抓住这个,但显然它没有。除非程序员依赖于id,否则它不会破坏某些东西。所以它有点像说:如果你足够愚蠢地编写这样的代码,那么你应该崩溃。
AAPT不会过多关心它。对于它来说,这就像是一个简单的视图扩展,没有程序员提供的明确的id。
答案 2 :(得分:2)
我认为只要标识符已经生成,它就会重复使用它。我倾向于重复使用ID,并且从未遇到过问题。