Search code examples
javaandroidandroid-databinding

How do I databind an object of the String[] type?


I already know that I can set the types for many other lists, but for String[] in particular, I currently am having to set the type as Object and cast it later to String[].

Using String[] is not accepted either.

e.g.

    <data>
        <variable name="example" type="Object" />
    </data>   

    <Linearlayout>
        <android.support.v7.widget.AppCompatSpinner
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:entries="@{(String[]) example}"/>
    </LinearLayout>

Solution

  • Looking further into the String[] type, it seems that it isn't a complete type (no size defined) and it doesn't validate any resources. The only valid collection types that the Android docs mention are in the following example:

    <data>
        <import type="android.util.SparseArray"/>
        <import type="java.util.Map"/>
        <import type="java.util.List"/>
        <variable name="list" type="List&lt;String&gt;"/>
        <variable name="sparse" type="SparseArray&lt;String&gt;"/>
        <variable name="map" type="Map&lt;String, String&gt;"/>
        <variable name="index" type="int"/>
        <variable name="key" type="String"/>
    </data>
    …
    android:text="@{list[index]}"
    …
    android:text="@{sparse[index]}"
    …
    android:text="@{map[key]}"