Search code examples
androidgenericsandroid-databinding

Data binding generic variable


How to define a generic type of a data binding variable?

The following code never compiles.

<data>
    <variable
        name="viewModel"
        type="com.example.viewmodel.ViewModel<Model>"/>
</data>

Solution

  • You need to escape <Model> as shown below:

    <data>
        <variable
            name="viewModel"
            type="com.example.viewmodel.ViewModel&lt;Model>"/>
    </data>
    

    Android Studio will still show a "Cannot resolve symbol" error, but the XML will compile. It is a known issue. From Android Studio Support for Data Binding:

    Note: Arrays and generic types, such as the Observable class, might display errors when there are no errors.