[英]android two-way binding /w LiveData using Java
I try to implement two way databinding in Java and I cant get it to work.我尝试在 Java 中实现两种方式的数据绑定,但我无法让它工作。 There seems to be not much material about that mostly Kotlin.
似乎没有太多关于 Kotlin 的材料。 What I have now:
我现在拥有的:
A simple ViewModel一个简单的视图模型
I had to make the MutableLiveData properties public
when I reference them via @={dashBoardViewModel.text}
, otherwise the compiler complained that it could not find FragmentDashBoardDataBindingImpl.当我通过
@={dashBoardViewModel.text}
引用 MutableLiveData 属性时,我必须public
它们,否则编译器会抱怨它找不到 FragmentDashBoardDataBindingImpl。
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class DashboardViewModel extends ViewModel {
public MutableLiveData<String> text;
public MutableLiveData<String> name;
public DashboardViewModel() {
text = new MutableLiveData<>();
name = new MutableLiveData<>();
text.setValue("This is the dashboard");
}
public void onSave() {
String oldValue = text.getValue();
String newValue = "new value " + name.getValue();
text.setValue(newValue);
}
}
A simple layout in a fragment:片段中的简单布局:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="dashBoardViewModel"
type="example.com.ui.dashboard.DashboardViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
...
tools:context=".ui.dashboard.DashboardFragment">
<TextView
android:id="@+id/text_dashboard"
...
android:text="@={dashBoardViewModel.text}"
... />
<EditText
...
android:inputType="textPersonName"
android:text="@={dashBoardViewModel.name}"
... />
<Button
...
android:onClick="@{() -> dashBoardViewModel.onSave()}"
...
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
In the constructor I call text.setValue("This is the dashboard")
which works fine and the value is displayed nicely.在构造函数中,我调用
text.setValue("This is the dashboard")
,它工作正常并且值显示得很好。
In the click listener dashBoardViewModel.onSave()
I can call text.setValue(newValue)
and it assigns the correct value but the value never gets displayed.在单击侦听
dashBoardViewModel.onSave()
中,我可以调用text.setValue(newValue)
并分配正确的值,但该值永远不会显示。
So text.setValue()
seems to work differently in the same class / same instance.所以
text.setValue()
似乎在同一个 class / 同一个实例中的工作方式不同。
Any hints would be very much appreciated.任何提示将不胜感激。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.