使用Java的android双向绑定/w LiveData
我试图用Java实现双向数据绑定,但我无法让它工作。关于科特林的资料似乎不多。我现在所拥有的: 简单的视图模型 当我通过使用Java的android双向绑定/w LiveData,java,android,two-way-binding,Java,Android,Two Way Binding,我试图用Java实现双向数据绑定,但我无法让它工作。关于科特林的资料似乎不多。我现在所拥有的: 简单的视图模型 当我通过@={dashBoardViewModel.text}引用MutableLiveData属性时,我必须将它们公开,否则编译器会抱怨它找不到碎片DashboardDataBindingImpl import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class
@={dashBoardViewModel.text}
引用MutableLiveData属性时,我必须将它们公开,否则编译器会抱怨它找不到碎片DashboardDataBindingImpl
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);
}
}
导入androidx.lifecycle.MutableLiveData;
导入androidx.lifecycle.ViewModel;
公共类DashboardViewModel扩展了ViewModel{
公共可变livedata文本;
公共可变livedata名称;
公共仪表板视图模型(){
text=新的可变LiveData();
name=新的MutableLiveData();
setValue(“这是仪表板”);
}
在save()上公开作废{
字符串oldValue=text.getValue();
字符串newValue=“new value”+name.getValue();
text.setValue(newValue);
}
}
片段中的简单布局:
<?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>
在构造函数中,我调用text.setValue(“这是仪表板”)
,它工作正常,值显示良好
在单击listenerdashBoardViewModel.onSave()
中,我可以调用text.setValue(newValue)
,它会指定正确的值,但从未显示该值
因此text.setValue()
在同一类/同一实例中的工作方式似乎不同
任何提示都将不胜感激。您可能忘记将
生命周期所有者
交给您的数据绑定
。你应该检查一下