搞定DataBinding-04

使用ObservableField

如果只需要更新部分字段,那么直接使用DataBinding提供的ObservableField就好,简洁方便。

定义ViewModel:isSelected

public class VehicleInfo extends BaseModel {

    public ObservableBoolean isSelected;
    
}

databinding布局

<layout >
    ...
    <data>

        <variable name="info" type="VehicleInfo"/>

    </data>

    <LinearLayout>
        ...

        <ImageView android:background="@{info.isSelected ? 1 : 2}" />
        ...
    </LinearLayout>
</layout>

更新数据:isSelected

   VehicleInfo data = binding.getInfo();

   data.isSelected.set(true);

使用 extends BaseObservable

只是ViewModel定义不同,使用方式同上。

定义ViewModel:isSelected

通过注解Bindable来说明get方法,拉取value。必须是getXXXX()
notifyPropertyChanged()某个字段更新

public class BaseObservableVehicleInfo extends BaseObservable {

    private boolean isSelected;

    @Bindable
    public boolean getIsSelected() {
        return isSelected;
    }

    public void setIsSelected(boolean isSelected) {
        this.isSelected = isSelected;
        notifyPropertyChanged(BR.isSelected);
    }

}

使用 implements Observable

如果不方便继承 BaseObservable,那只好实现Observable接口了。

定义ViewModel:isSelected

只需要实现add/remove/notify

public class ObservableVehicleInfo implements Observable {

    private boolean isSelected;

    @Bindable
    public boolean getIsSelected() {
        return isSelected;
    }

    public void setIsSelected(boolean isSelected) {
        this.isSelected = isSelected;
        notifyPropertyChanged(BR.isSelected);
    }


    //for data binding Observable
    private transient PropertyChangeRegistry mCallbacks;
    @Override
    public synchronized void addOnPropertyChangedCallback(OnPropertyChangedCallback onPropertyChangedCallback) {
        if (mCallbacks == null) {
            mCallbacks = new PropertyChangeRegistry();
        }
        mCallbacks.add(onPropertyChangedCallback);
    }

    @Override
    public synchronized void removeOnPropertyChangedCallback(OnPropertyChangedCallback onPropertyChangedCallback) {
        if (mCallbacks != null) {
            mCallbacks.remove(onPropertyChangedCallback);
        }
    }

    public synchronized void notifyChange() {
        if (mCallbacks != null) {
            mCallbacks.notifyCallbacks(this, 0, null);
        }
    }


    public void notifyPropertyChanged(int fieldId) {
        if (mCallbacks != null) {
            mCallbacks.notifyCallbacks(this, fieldId, null);
        }
    }
}

GitHub地址

AndroidDataBindingTutorial

发表评论

电子邮件地址不会被公开。 必填项已用*标注