【发布时间】:2016-07-31 13:11:22
【问题描述】:
我一直在尝试使用 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() 来强制绑定 - 但这是一个非常丑陋的解决方案
【问题讨论】:
标签: android data-binding android-databinding