我想使用自定义@BindingAdapter通过LiveData设置TextView的文本。
TextView:
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:gravity="center"
app:keyToText='@{viewmodel.getText("TI_001")}'/>
BindingAdapter:
@BindingAdapter("keyToText")
public static void setTextViewText(TextView tv, LiveData<String> data) {
if (data == null || data.getValue() == null) {
tv.setText(null);
} else {
tv.setText(data.getValue());
}
}
使用调试器,我已经检查数据对象是否具有正确的值,
但是不幸的是data.getValue()始终返回null,因此文本未设置为提供的TextView。
我想念什么吗?我真的需要这样做才能...希望。
更新
将生命周期所有者设置为绑定,如下所示:
mBinding.setLifecycleOwner(this);
当我使用
viewModel.getText("TI_001").observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
tv.setText(s);
}
});
我可以毫无问题地读取观察到的LiveData的值。
更新2
Viewmodels getText方法:
public LiveData<String> getText(String key){
return textRepository.getText(key);
}
textRepository的getText方法:
public LiveData<String> getText(String id){
return textDao.findById(id);
}
还有textDao的findById方法:
@Query("SELECT text.text FROM text WHERE text.id LIKE :id")
LiveData<String> findById(String id);
答案 0 :(得分:0)
我可能已经找到解决问题的方法:
@BindingAdapter("keyToText")
public static void setTextViewText(TextView tv, LiveData<String> data) {
if (data == null) {
tv.setText(null);
} else {
data.observeForever(new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
tv.setText(data.getValue());
data.removeObserver(this);
}
});
}
}
因此,我基本上只观察第一个onChanged事件的LiveData,并在设置文本后立即删除使用的观察者。