Android Jetpack components use observable data objects

PS: The original text was first published on WeChat public account: Jongxingzhi (jzman-blog)

Observability refers to the ability of an object to notify other data. There are three main types of observability:

  1. Field
  2. Object
  3. set

Using data binding can provide the data object with the ability to notify other data changes when the data changes, bind an observable data object to the UI, and automatically update the UI when the properties of the data object change.

Field

If a class has only a few attributes, in order to make these objects have the ability to observe data changes, they can be implemented using Observable fields. Databinding provides such a generic Observable class, including eight basic data types and Parcelable Types are as follows:

  • ObservableBoolean
  • ObservableByte
  • ObservableChar
  • ObservableShort
  • ObservableInt
  • ObservableLong
  • ObservableFloat
  • ObservableDouble
  • ObservableParcelable

Let's use it. Here we use strings and Int to illustrate the use of observable fields. First, create an entity class as follows:

/**
 * Powered by jzman.
 * Created on 2018/12/3 0003.
 */
public class Person {
    
    
    public final ObservableField<String> name = new ObservableField<>();
    public final ObservableInt age = new ObservableInt();
}

Then, declare the variables to be used in the layout file, as follows:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable
            name="person"
            type="com.manu.databindsample.data.Person"/>
    </data>

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{`name is `+person.name+`,age is `+person.age}"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="btnClickObservableField"
            android:text="可观察字段"/>

    </LinearLayout>
</layout>

Then, bind the data object in the corresponding Activity, as follows:


private Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    ActivityObservableObjectSampleBinding binding =
            DataBindingUtil.setContentView(this,R.layout.activity_observable_object_sample);
    person = new Person();
    binding.setPerson(person);
}

Finally, dynamically modify the value of person. When the attribute value of the Person object changes, its attribute value will be dynamically updated, and then the UI will be dynamically updated, as follows:

//动态修改属性值
public void btnClickObservableField(View view) {
    
    
    person.name.set("android");
    person.age.set(10);
}

The above is the use of observable fields. The key is the observer design mode. At the end of the article, see the test effect diagram.

Object

When using databinding, databinding provides an interface android.databinding.Observable, a listener can be registered when a certain class implements this interface, and the listener will monitor the changes of a certain data object, and then notify the attribute of the data object Change, this Observable interface has a mechanism to add and delete listeners, but when to send data update notifications is determined by the specific implementation class. In order to simplify development, you can use the provided BaseObserable, which implements the listener registration mechanism. The class that inherits BaseObservable determines when the property changes, that is, use the annotation @Bindable on the corresponding getter method, and call the corresponding notifyPropertyChanged method on the corresponding setter method. Let’s take a look at the specific usage of the observable object. First, create A data entity class is as follows:

/**
 * 可观察的数据对象
 * Powered by jzman.
 * Created on 2018/12/4 0004.
 */
public class Student extends BaseObservable{
    
    
    private String name;
    private int age;

    @Bindable
    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
        notifyPropertyChanged(BR.name);
    }

    @Bindable
    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
        notifyPropertyChanged(BR.age);
    }
}

Then, declare the variables to be used in the layout file, as follows:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable
            name="student"
            type="com.manu.databindsample.data.Student"/>
    </data>

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{`name is `+student.name+`,age is `+student.age}"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="btnClickObservableObject"
            android:text="可观察对象"/>

    </LinearLayout>
</layout>

Then, bind the data object in the corresponding Activity, as follows:


private Student student;
@Override
protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    ActivityObservableSampleBinding binding =
            DataBindingUtil.setContentView(this,R.layout.activity_observable_sample);
    //可观察对象
    student = new Student();
    binding.setStudent(student);
}

Finally, dynamically modify the value of the student. When the attribute value of the Student object changes, its attribute value will be dynamically updated, and then the UI will be dynamically updated, as follows:

public void btnClickObservableObject(View view) {
    
    
    student.setName("可观察对象");
    student.setAge(20);
}

The above is the use of observable objects, see the test effect diagram at the end of the article.

set

Collection data is often involved in the development process. Databinding also provides collection classes with observation capabilities. Here, the most commonly used Map and List collections are used to illustrate the use of ObservableMap and ObservableList. First, declare the variables to be used in the layout file. ,details as follows:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <!--ArrayMap-->
        <import type="android.databinding.ObservableArrayMap"/>
        <variable
            name="arrayMap"
            type="ObservableArrayMap&lt;String,String>"/>
        <!--ArrayList-->
        <import type="android.databinding.ObservableList"/>
        <variable
            name="arrayList"
            type="ObservableList&lt;String>"/>
    </data>

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{`name is `+arrayMap.name+`,age is `+arrayMap.age}"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="btnClickObservableMap"
            android:text="可观察集合之ArrayMap"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{`name is `+arrayList[0]+`,age is `+arrayList[1]}"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="btnClickObservableList"
            android:text="可观察集合之ArrayList"/>
    </LinearLayout>
</layout>


Then, bind and data objects in the corresponding Activity, as follows:

private ObservableArrayMap<String,String> arrayMap;
private ObservableArrayList<String> arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    ActivityObservableSampleBinding binding =
            DataBindingUtil.setContentView(this,R.layout.activity_observable_sample);
    //可观察集合之ArrayMap
    arrayMap = new ObservableArrayMap<>();
    binding.setArrayMap(arrayMap);
    //可观察集合之ArrayList
    arrayList = new ObservableArrayList<>();
    binding.setArrayList(arrayList);
}

Finally, after binding the collection data, you can modify the collection data to observe the changes in the UI, as follows:

//可观察集合之ArrayMap
public void btnClickObservableMap(View view) {
    
    
    arrayMap.put("name","可观察集合之ArrayMap");
    arrayMap.put("age","30");
}

//可观察集合之ArrayList
public void btnClickObservableList(View view) {
    
    
    arrayList.add("可观察集合之ArrayList");
    arrayList.add("40");
}

The above is the use of observable sets.

Test effect

Through the above small case, I believe that the fields, objects, and collections with observation capabilities provided by databinding can be used very easily. The following is the test effect diagram of the above code:

jzman-blog
Pay attention to communicate and learn together.
Insert picture description here

Guess you like

Origin blog.csdn.net/jzman/article/details/107031312