Android 双向数据绑定无法触发事件 onCheckedChanged

Android two-way databinding cannot get event onCheckedChanged to fire

除非调用 executePendingBindings,否则我无法触发 OnCheckedChangeListener。但是,如果我这样做,Item.java 中的 setChecked 事件不会被调用。

如何让 setChecked 和 OnCheckedChangeListener 都被调用?

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="item"
            type="com.example.abc.twowaydatabinding.Item" />
    </data>

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

        <Switch
            android:id="@+id/switch_test"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="@={item.checked}" />

    </LinearLayout>
</layout>

Item.java

import android.databinding.BaseObservable;
import android.databinding.Bindable;

public class Item extends BaseObservable {
    private String name;
    private Boolean checked;
    @Bindable
    public String getName() {
        return this.name;
    }
    @Bindable
    public Boolean getChecked() {
        return this.checked;
    }
    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }
    public void setChecked(Boolean checked) {
        this.checked = checked;
        notifyPropertyChanged(BR.checked);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    public Item item;
    ActivityMainBinding binding;
    Switch switch_test;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        item = new Item();

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        binding.setItem(item);

        switch_test = findViewById(R.id.switch_test);

        ///binding.executePendingBindings(); -->this will fire OnCheckedChangeListener

        switch_test.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "checked", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "not checked", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}

这对我来说并不奇怪,因为我知道点击侦听器以这种方式工作(只能有一个)。我处理点击的一种方法是 onTouchHandler,但我认为这里更好的方法是使用 item.addOnPropertyChangedCallback() 而不是 setOnCheckedChangedListener()。数据绑定的好处之一是您可以实现 MVVM 模式,其中 ViewModel 与 UI 细节分离。在这种情况下,您可以将实现从 Switch 更改为其他内容,并且您的 activity 代码不必更改(并且您可以消除 findViewById() 调用)。