The Java-android 2 way data binding (bind) sample does not work as described

android 2 way data binding (bind) sample does not work as described… here is a solution to the problem.

android 2 way data binding (bind) sample does not work as described

I read this article About 2 ways of Android data binding (bind).

I

noticed that the code was a bit fuzzy, so I decided to implement a workable example and put it on github so others could more easily dive into it. But following the instructions provided in this article, I can’t get it to work.

In my example, I only have the main activity and switcher, custom controls, and switcher. So when I check the main switcher, it refreshes everything correctly and works as expected, but when I check/uncheck the inner switcher, it doesn’t affect the main view model and any activities – so the 2-way binding (bind) doesn’t work.

Please help me find out why this is happening and fix the problem.


The code has been fixed and now works at least as expected in Android Studio 2.2 beta 1.

Link to the code sample on github

Solution

You have almost everything connected correctly. In CustomSwitcher, there is no notification when the value of the internal switcher changes. You must listen for the change and invoke the onValChanged callback.

Here is your code:

public CustomSwitcher(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.binding = CustomSwitcherBinding.inflate(LayoutInflater.from(context), this, true);
}

public void setVm(boolean vmVal){
    this.vm = vmVal;
    this.binding.setItem(vm);
}

Bloated binding (bind) does not notify the custom switcher directly, so you must listen for that event. Then you have to invoke the listener. You must also make sure that you do not set the same value that already exists, thus avoiding an infinite loop of notifying the same value over and over again.

public CustomSwitcher(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.binding = CustomSwitcherBinding.inflate(LayoutInflater.from(context), this, true);
    this.binding.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            if (propertyId == BR.item) {
                setVm(binding.getItem());
            }
        }
    });
}

public void setVm(boolean vmVal){
    if (vmVal != this.vm) {
        this.vm = vmVal;
        this.binding.setItem(vm);
        if (this.onValChanged != null) {
            this.onValChanged.onValChanged(this, vmVal);
        }
    }
}

Related Problems and Solutions