0

我想使用自定义 @BindingAdapter 来使用 LiveData 设置 TextView 的文本。

文本视图:

<TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:gravity="center"
       app:keyToText='@{viewmodel.getText("TI_001")}'/>

绑定适配器:

@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);
4

1 回答 1

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,并在设置文本后立即删除使用的观察者。

于 2019-01-20T16:17:46.640 回答