Android数据绑定mCallback始终为null

时间:2016-07-31 13:11:22

标签: android data-binding android-databinding

我已经在尝试使用Android数据绑定库,请参阅Google开发者指南。但即使完全遵循他们的代码notifyPropertyChanged()也无法正常工作。

BaseObservable中的mCallbacks始终为空。我已经调试了代码,因为绑定已经设置并调用了addOnPropertyChangedCallback并且设置了mCallbacks,但是由于某种原因,这个引用在你调用notifyPropertyChanged()时已经丢失了。

可能有些东西我不知道,所以任何帮助都会非常感激!

代码:

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()强制绑定 - 但这是一个非常丑陋的解决方案

1 个答案:

答案 0 :(得分:0)

您可以使用executePendingBindings(),它将执行所有已更改且需要更新的绑定。

binding.executePendingBindings();

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

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