引用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的控件。
java 中根据“hello”字符串获取
int tvid = getResources().getIdentifier("hello", "id", mContext.getPackageName());
注:第二个参数写"id"与写"string"结果不一样
int itemId = getResources().getIdentifier("item_i_1", "layout", mContext.getPackageName()); 这样可直接获取layout文件下xml 的id