Search code examples
androidviewattributesincludeparameterized

Modifying nested attributes on an included Layout


I've been learning about merge and include lately, and I have a question I can't seem to figure out the answer too. Say I have a layout that defines a header component that I want to add to multiple layouts. However, I want to change the title, or icon of each header per each include usage. For example say I have the following layout:

<RelativeLayout android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                style="@style/menu_header">

    <Button android:id="@+id/backButton"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/button"
            android:text="@string/back"/>

    <TextView style="@style/headerTitle"
              android:layout_centerInParent="true"
              android:text="${title}"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content"/>
</RelativeLayout>

Then I can include that in other layouts using:

<LinearLayout ...>
   <include android:id="@+id/searchHeader" layout="@layout/shared_header" title="Search"/>
   ...
</LinearLayout>

I know I can modify any layout_* attribute of the root element, but can I define other attributes that get substituted into the layout, like say "title" in this example, without having to create my own subclass of View, add declare-styleable definitions in valaues/resources, etc?

Having something like this would make creating reusable views so much simpler, but I can't seem to find any evidence that says if merge + include can do it.


Solution

  • The answer is nope. Unfortunately, Android isn't that powerful. You have to create your own extension of ViewGroup and write more code.