androidandroid-layoutnested-properties

Can you set a view as a property of another view in an XML layout file?


We have a custom GridView which has headerView and footerView properties. I'm wondering if in Android, it's possible to set those properties from within a layout file.

XAML in Windows lets you do this easily since you can specify properties either via attributes (for things like strings, numbers or other simple types), or via nested elements (for any object type) with a ControlType:PropertyName syntax.

Here's a pseudo-version of what this would look like if Android supported something similar:

<MyCustomGrid
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <!-- This would set the 'headerView' property
         on 'MyCustomGrid' to a TextView -->
    <MyCustomGrid:headerView>

        <TextView android:text="I'm the Header TextView" />

    </MyCustomGrid:headerView>

</MyCustomGrid>

Obviously the above is not valid. But is it possible to do something similar in Android, or do I have to do it in the code-behind in the Activity/Fragment?


Solution

  • Yes, you can.

    You can create a Custom View by extending the GridView class and add some logic through attributes. This will not work as an attached property from XAML (Like Grid.Column or Grid.Row from XAML UWP) but you can do something like this:

    <com.teste.widget.MarqueIVGridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:my_header="@layout/my_header"
    />
    

    Don't forget to add the namespace at the root of your layout:

    xmlns:app="http://schemas.android.com/apk/res-auto"
    

    Google has this sample: HeaderGridView

    It uses a different approach, if you copy this class you will just need to use this "HeaderGridView" and call addHeaderView method from it sending your header view inflated.

    Feel free to ask any question and It will be a pleasure to answer.