Cannot reference Observable Class fields from xml layout

I am watching a new Data Binding plugin for Android and trying to integrate it into a project.

When reading about creating observable objects, I came across the ObservableFields documentation, which uses an example of stand-alone observable objects from the documentation:

public class User extends BaseObservable { public final ObservableField<String> firstName = new ObservableField<>(); public final ObservableField<String> lastName = new ObservableField<>(); public final ObservableInt age = new ObservableInt(); } 

Above the fragment there will be a replacement:

 private static class User extends BaseObservable { private String firstName; private String lastName; @Bindable public String getFirstName() { return this.firstName; } @Bindable public String getFirstName() { return this.lastName; } public void setFirstName(String firstName) { this.firstName = firstName; notifyPropertyChanged(BR.firstName); } public void setLastName(String lastName) { this.lastName = lastName; notifyPropertyChanged(BR.lastName); } } 

Which is significantly less code; But when using Observable Fields and links, then from an XML layout, for example:

 <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="user" type="com.example.User"/> </data> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{user.lastName}" android:id="@+id/lastName"/> </LinearLayout> </layout> 

I get this error:

 ../../databinding/ActivityMainBinding.java Error:(127, 20) error: cannot find symbol variable lastName 

And this is not verbose; Do not use ObservableFields works like a charm.

Documentation Link

Anyone facing this problem? Thoughts?

+6
source share
2 answers

This seems like a mistake at our end. I heard that adding @Bindable fixes the problem, but data binding should be able to find it without Bindable annotation. I created an error inside, thanks.

+5
source

ObservableField must be annotated with @Bindable annotation for compilation.

Source for Bindable annotation:

it is necessary for the java analyzer to work

So it looks like this:

 public class User extends BaseObservable { @Bindable public final ObservableField<String> firstName = new ObservableField<>(); @Bindable public final ObservableField<String> lastName = new ObservableField<>(); @Bindable public final ObservableInt age = new ObservableInt(); } 
+1
source

Source: https://habr.com/ru/post/988313/


All Articles