Referencing Android layout elements before defining them

by

Occasionally it’s convenient to have an Android RelativeLayout that references another layout element that hasn’t been defined at that point in the XML file. E.g.:

<RelativeLayout ... >
    <View
        android:id="@+id/top_view"
        android:layout_above="@id/bottom_view"
        ... />
    <View
        android:id="@+id/bottom_view"
        ... />
</RelativeLayout>

This won’t compile with the error “No resource found that matches the given name“, because the bottom_view ID is being referenced before it’s been defined.

Some people solve this by changing the order of the layout elements in the XML file—it’s a RelativeLayout so elements need to be explicitly positioned regardless—but that’s a bad way to do it. If one view appears before/atop another in the app, it should appear before it in the source.

Another mis-solution that I’ve seen is adding an ID in ids.xml. This works, but is unnecessary.

The right solution is to add the ID the first time it’s referenced: android:layout_above="@+id/bottom_view". Then, when the element’s actually defined, just reference the already existing ID: android:id="@id/bottom_view". The whole piece will then look like this:

<RelativeLayout ... >
    <View
        android:id="@+id/top_view"
        android:layout_above="@+id/bottom_view"
        ... />
    <View
        android:id="@id/bottom_view"
        ... />
</RelativeLayout>

Leave a Reply

Your email address will not be published. Required fields are marked *