Pages

Thursday, July 28, 2011

What does "@+id" mean?

One thing I've discovered recently is how the "@+id/" works in the layout files. 

Most tutorials show you adding android:id="@+id/id_name" to the View element in the layout xml file.  Then if you have to refer to the id in another element (say, to position it in a RelativeLayout) you refer to it without the "+" (i.e. android:id=@id/id_name.)  It gives the impression that the rule is you simply use the + when indicating a View's id, but not when you are referring to another View's id.

Actually, that's not how it works.  Really the rule is that you use the + when you are introducing a new id that you have not used before, then leave out the + when referring to a previously used id.  Most often you'll end up using the id for the first time when defining a View's id, so most people can remain oblivious of how it really works.

Why would you refer to a View before creating it?  You might wish to do that with a RelativeLayout, aligning a View with one you will be defining later in the file, as with this example:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="blue"
        android:background="#ff0000ff"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:id="@+id/blue"
        android:layout_toLeftOf="@+id/red"
    />
    <TextView
        android:id="@id/red"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="red"
        android:background="#ffff0000"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
    />
</RelativeLayout>

That will produce the following, in which the "blue" View can be positioned to the left of the "red" View, even though "red" isn't defined until later in the file:

No comments:

Post a Comment