Defining Your Own Resource IDs for Later

The general pattern for allocating an id is either to create a new one or to use the one created by the Android package. However, it is possible to create ids beforehand and use them later in your own packages.

The line <TextView id="@+id/text"> in the preceding code segment indicates that an id named text is going to be used if one already exists. If the id doesn't exist, then a new one is going to be created. So when might an id such as text already exist in R.java for it to be reused?

You might be inclined to put a constant like R.id.text in R.java, but R.java is not editable. Even if it were, it gets regenerated every time something gets changed, added, or deleted in the /res/* subdirectory. However, you can use a resource tag called item to define an id without attaching to any particular resource. Here is an example:

<resources>

<item type="id" name="text"/> </resources>

The type refers to the type of resourceā€”an id in this case. Once this id is in place, the following View definition would work:

<TextView android:id="@id/text"> </TextView>

0 0

Post a comment