[英]Databinding - ObservableField<String> not updating view
I have simple app - Button
- which fetches data from rest api and a TextView
where this data is displayed.我有一个简单的应用程序 -
Button
- 它从 rest api 和一个显示此数据的TextView
获取数据。 I'm using MVVM architectural pattern.我正在使用MVVM架构模式。 When ViewModel receives callback with fetched data I set it up to an ObservableField.
当ViewModel收到带有获取数据的回调时,我将其设置为 ObservableField。 Unfortunately it doesn't update text on the screen, but whenever I rotate device data is being updated on the screen.
不幸的是它不会更新屏幕上的文本,但是每当我旋转设备数据时都会在屏幕上更新。
OK, enough talking, I'll show you the code:好了,废话不多说,我给你看代码:
ViewModel视图模型
public class MyViewModel extends ViewModel{
private ObservableField<String> name = new ObservableField<>();
@Override
public void onListReceived(String username) {
super.onListReceived(list);
name.set(username);
}
public String getName() {
return name.get();
}}
and in XML:并在 XML 中:
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{viewModel.name}"
tools:text="some text"/>
As far as I read, I think it should be '=' in this line android:text="@{viewModel.name}"
between ' @
' and ' {
', but when I add it, clean project and rebuild this, I got an error that Cannot resolve DataBindingComponent
.据我阅读,我认为它应该是 '=' 在这一行
android:text="@{viewModel.name}"
之间 ' @
' 和 ' {
',但是当我添加它时,清理项目并重建它,我收到了无法解析DataBindingComponent
的错误。
Any ideas?有任何想法吗?
Thanks in advance!提前致谢!
Remove the getName()
method, and make name
be public
.删除
getName()
方法,并将name
设为public
。 Or, have getName()
return name
, not name.get()
.或者,让
getName()
返回name
,而不是name.get()
。
The data binding system needs to be working directly with the Observable
.数据绑定系统需要直接使用
Observable
。 Right now, your Observable
is hidden from data binding, and so data binding has no way of registering an observer and knowing when the data changes.现在,您的
Observable
对数据绑定是隐藏的,因此数据绑定无法注册观察者并知道数据何时发生变化。
As far as I read, I think it should be '=' in this line android:text="@{viewModel.name}" between '@' and '{',
据我所知,我认为它应该是 '=' 在这一行 android:text="@{viewModel.name}" 之间 '@' 和 '{',
That syntax ( @={viewModel.name}
) is for two-way data binding.该语法(
@={viewModel.name}
)用于双向数据绑定。 Since the user cannot enter data into a TextView
, that is not needed here.由于用户无法在
TextView
输入数据,因此这里不需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.