Bolein95
Bolein95

Reputation: 3056

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>

Upvotes: 28

Views: 11396

Answers (4)

user1540907
user1540907

Reputation: 201

You can set something like examples above:

<data>
    <import type="com.example.path.Model"/>
    <variable
        name="obj"
        type="com.example.viewmodel.ViewModel&lt;Model&gt;"
        />
</data>

NOTE: you can write '>' or '&gt;' at end of Model should be OK

To avoid error display do not forget to add line to tell what object type is used:

<import type="com.example.path.Model"/>

Upvotes: 4

Hasan Abdullah
Hasan Abdullah

Reputation: 2668

Try this one:

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

&lt; is responsible for < and &gt; is responsible for >.

Upvotes: 8

Mark Lu
Mark Lu

Reputation: 1358

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.

Upvotes: 42

anthropic android
anthropic android

Reputation: 364

You have a left triangle bracket in XML; XML don't play that way. try

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

Upvotes: 1

Related Questions