Chickin Nick Chickin Nick - 1 month ago 7
Android Question

How to bind object with two layouts?

I have such Model

public class MyCheckedVM extends BaseObservable {
@Bindable
ObservableBoolean observableBoolean = new ObservableBoolean();


@Bindable
public ObservableBoolean getObservableBoolean() {
return observableBoolean;
}

@Bindable
public void setObservableBoolean(ObservableBoolean observableBoolean) {
this.observableBoolean = observableBoolean;
}

public void onCheckChanged(CompoundButton view, boolean isChecked) {
Log.d(TAG, "onCheckChanged");

}


This model I set to Main activity binding with
ToggleButton
and inside
Fragment
which has such button too

<ToggleButton
android:onCheckedChanged="@{viewModel.onCheckChanged}"
android:checked="@{viewModel.observableBoolean}"
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


But when i try to click on any button, all of them are changing independently of each other. Maybe it is wrong way how I bind model to
Fragmnet


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentExampleBinding fragmentExampleBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_example, container, false);

fragmentExampleBinding.setViewModel(((MainActivity) getActivity()).getViewModel()); //getter in MainActivity for instance of viewModel

return fragmentExampleBinding.getRoot();
}

Answer

One problem I see is your use of setObservableBoolean. You have a BaseObservable so you should notify the property change if you call a setter.

But that's only because you're using ObservableBoolean in an unusual manner. Best practice is to always use them as public final fields. If you do this, you don't need to use BaseObservable as a base class:

public class MyCheckedVM {
    public final ObservableBoolean observableBoolean = new ObservableBoolean();

    public void onCheckChanged(CompoundButton view, boolean isChecked) {
        Log.d(TAG, "onCheckChanged");
    }
}

You can mix observable fields in an Observable class (or BaseObservable). Just make your observable fields public final and make sure to call notifyPropertyChanged(BR.myField) inside the setters of bindable properties.