Android开放中要想得到布局文件中控件的引用,该控件必须设置id属性,这两有两种方式设置id:(1)@+id/xxxx;(2)@id/xxxx;下面做个简单的介绍。

@+id/xxx:如果R文件中没有该id则创建;

注意:一个xml文件中不能出现两个以该形式设置同一id的两个控件(include标签例外);

示例1 正确的使用:

<TextViewandroid:id="@+id/mytv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="helloworld"/>

示例2 错误(两个id相同):此时系统会提醒报错

<TextViewandroid:id="@+id/mytv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="helloworld"/><TextViewandroid:id="@+id/mytv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="helloworld"/>

示例3 允许以下用法,但是该id指向的是include标签,之后的linearLayout设置id的操作无意义:

<includeandroid:id="@+id/include1"layout="@layout/my"android:layout_width="50dp"android:layout_height="50dp"/><LinearLayoutandroid:id="@+id/include1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"/>

如果将include标签与LinearLayout交换位置则会报错。

示例 4 允许以下用法,但是该id指向TextView,之后的include标签和LinearLayout设置id无意义:

<TextViewandroid:id="@+id/mytv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="helloworld"/><includeandroid:id="@id/mytv"layout="@layout/my"android:layout_width="50dp"android:layout_height="50dp"/><LinearLayoutandroid:id="@id/mytv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"/>

如果将TextView的位置下移,运行会出错。如果include中引用的布局存在与TextView相同的id设置,不会报错但是无意义。

2.@id/xxxx:引用ids.xml中相应的id,与@+id/xxx不同,一旦向ids.xml文件中添加一个id在R.java文件中会生成一个相应的id,无论是否有控件使用该id。

使用示例:

(1)创建ids.xml

<resources><itemname="hello"type="id"/><itemname="hello2"type="id"/><itemname="hello3"type="id"/><itemname="hello4"type="id"/><itemname="hello5"type="id"/><itemname="hello6"type="id"/><itemname="hello7"type="id"/><itemname="hello8"type="id"/></resources>

(2)使用id

<TextViewandroid:id="@id/hello"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="hello1"/><TextViewandroid:id="@id/hello"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="hello2"/><TextViewandroid:id="@id/hello"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="hello3"/>

多个控件可以以同样的方式设置统一id,但是该id只属于最先使用该id的控件。