Chickin Nick Chickin Nick - 1 year ago 73
Android Question

How to bind object with two layouts?

I have such Model

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

public ObservableBoolean getObservableBoolean() {
return observableBoolean;

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
and inside
which has such button too

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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download