Android开放中要想获得布局文件中控件的引用,该控件必须设置id属性,这两有两种方式设置id:(1)@+id/xxxx;(2)@id/xxxx;下面作个简单的介绍。java
@+id/xxx:若是R文件中没有该id则建立;android
注意:一个xml文件中不能出现两个以该形式设置同一id的两个控件(include标签例外);ide
示例1 正确的使用:布局
<TextView android:id="@+id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world"/>
示例2 错误(两个id相同):此时系统会提醒报错
xml
<TextView android:id="@+id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world"/> <TextView android:id="@+id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world"/>
示例3 容许如下用法,可是该id指向的是include标签,以后的linearLayout设置id的操做无心义:ci
<include android:id="@+id/include1" layout="@layout/my" android:layout_width="50dp" android:layout_height="50dp"/> <LinearLayout android:id="@+id/include1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"/>
若是将include标签与LinearLayout交换位置则会报错。it
示例 4 容许如下用法,可是该id指向TextView,以后的include标签和LinearLayout设置id无心义:io
<TextView android:id="@+id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world"/> <include android:id="@id/mytv" layout="@layout/my" android:layout_width="50dp" android:layout_height="50dp"/> <LinearLayout android:id="@id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"/>
若是将TextView的位置下移,运行会出错。若是include中引用的布局存在与TextView相同的id设置,不会报错可是无心义。class
2.@id/xxxx:引用ids.xml中相应的id,与@+id/xxx不一样,一旦向ids.xml文件中添加一个id在R.java文件中会生成一个相应的id,不管是否有控件使用该id。引用
使用示例:
(1)建立ids.xml
<resources> <item name="hello" type="id" /> <item name="hello2" type="id" /> <item name="hello3" type="id" /> <item name="hello4" type="id" /> <item name="hello5" type="id" /> <item name="hello6" type="id" /> <item name="hello7" type="id" /> <item name="hello8" type="id" /> </resources>
(2)使用id
<TextView android:id="@id/hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello 1" /> <TextView android:id="@id/hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello 2" /> <TextView android:id="@id/hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello 3" />
多个控件能够以一样的方式设置统一id,可是该id只属于最早使用该id的控件。