Android 数据绑定 mCallback 始终为空

Android Data Binding mCallback is always null

我一直在试验 Android 数据绑定库,遵循 google 开发人员指南。但即使完全遵循他们的代码 notifyPropertyChanged() 也永远行不通。

mCallbacks 在 BaseObservable 中始终为 null。我已经在设置绑定、调用 addOnPropertyChangedCallback 和设置 mCallbacks 时调试了代码,但是由于某种原因,当你开始调用 notifyPropertyChanged().[= 时,这个引用已经丢失了17=]

我可能遗漏了一些东西,如有任何帮助,我们将不胜感激!

代码:

public class TestActivity extends AppCompatActivity {

TestModel mTestModel;
ActivityTestBinding mBinding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBinding = DataBindingUtil.setContentView(this, R.layout.activity_test);
    mTestModel = new TestModel("Test", "User");
    mBinding.setTestModel(mTestModel);

    mBinding.ratingBtnUpdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mTestModel.setFirstName("New");
            mTestModel.setLastName("WOOOOORKS");
            mBinding.notifyPropertyChanged(BR.firstName);
        }
    });
}}


public class TestModel extends BaseObservable {

private String firstName;
private String lastName;

public TestModel(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

@Bindable
public String getFirstName() {
    return this.firstName;
}

@Bindable
public String getLastName() {
    return this.lastName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}}

布局:

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    >


    <data>
        <variable
            name="testModel"
            type="com.boundless.happymeter.model.TestModel"
            />
    </data>


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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{testModel.firstName}"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{testModel.lastName}"
            />

        <Button
            android:id="@+id/rating_btn_update"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:text="Update"
            />

    </LinearLayout>


</layout>

注意: 可以使用 mBinding.invalidateAll() 强制绑定 - 但这是一个非常丑陋的解决方案

你可以使用executePendingBindings(),它会执行所有改变和需要更新的绑定。

binding.executePendingBindings();

其他解决方案是您可以在所有 setter 方法中使用 notifyPropertyChanged();

public void setFirstName(String firstName) {
    this.firstName = firstName;
    notifyPropertyChanged(BR.firstName);
}