Why declaring @+id is allowed in other than id attributes

88 Views Asked by At

So lastly I have had to rebuild not my XML layout file for android app. And I saw constructions like

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:id="@+id/rev_main"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rev_arrow">
        <!-- some stuff in here -->
    </LinearLayout>
    <ImageView
        android:id="@+id/rev_arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/arrow"
        />
</RelativeLayout>

It is really annoying when I see that someone using @+id in not android:id attribute. When any developer will want to search this id he will find LinearLayout first instead ImageView. My question is why google allow it? Is there any particular reason for it and I just didn't know it?

Sorry for my poor English.

2

There are 2 best solutions below

0
On BEST ANSWER

Yes, there is a reason: Sometimes, you have to set a View A relative to the position of a View B which is declared later in the XML-file (which is the case in your example. The LinearLayout is "View A" and the ImageView is "View B").

Imagine, the code you've got a problem with

android:layout_below="@+id/rev_arrow"

would look like this instead:

android:layout_above="@+id/rev_arrow"

The android:layout_above would be useless if you couldn't declare an id inside it.

Because it was mentioned in a few comments: You have to use the "plus"-sign always at that place, where the id is first declared in the layout-file (from top to bottom). It is independet from the attribute, like "id" or "layout_below".

3
On

This is a valid use of the ID, as it tells the layout manager that the view identified by id/rev_main view is to be placed below the view identified by id/rev_arrow.

So in places other than android:id, the ids are used as references to views identified by the respective id.