深入理解android:id以及@+id/name和@id/name的区别联系

今天为了好好研究了下@+id/name和@id/name的区别以及联系,又翻了翻文档/guide/topics/resources/layout-resource.html中关于

android:id的介绍,

Value for android:id
For the ID value, you should usually use this syntax form: "@+id/name". The plus symbol, +, indicates that this is a new resource ID and the aapt tool will create a new resource integer in the R.java class, if it doesn't already exist. For example:

<TextView android:id="@+id/nameTextbox"/>
The nameTextbox name is now a resource ID attached to this element. You can then refer to the TextView to which the ID is associated in Java:

findViewById(R.id.nameTextbox);
This code returns the TextView object.

However, if you have already defined an ID resource (and it is not already used), then you can apply that ID to a View element by excluding the plus symbol in the android:id value.

然后自己又实验了一下,发现:

@+id/name和@id/name的相同之处是当id已经定义过时它们都会返回一个id值,这时它们作用一样。

不同之处是如果这个id还没有定义过,那么@+id/name将会使aapt tool生成(即定义)一个id值,并返回这个id值,而@id/name则会导致报错,提示id值未找到。

这时突然产生一个有趣的念头:我们完全可以在任何需要提供id值的地方都使用@+id/name,而不使用@id/name,因为使用@+id/name时,如果id已经定义过就不会重新定义一个id。如下图:

 

而且定义id也不一定非得以android:id="@+id/name"的形式,可以在任何接受id值的地方定义,然后android:id处直接使用。如下图:

 

当然了这样混用容易使其他人产生疑惑,个人认为,在定义Id的地方才使用@+id/name的形式,而在使用Id的地方使用@id/name应该更合适些。

posted @ 2016-12-16 10:27  xxNote  阅读(2178)  评论(0编辑  收藏  举报