【问题标题】:android two-way binding /w LiveData using Javaandroid 双向绑定/w LiveData 使用Java
【发布时间】:2020-12-14 18:18:35
【问题描述】:

我尝试在 Java 中实现两种方式的数据绑定,但我无法让它工作。似乎没有太多关于 Kotlin 的材料。我现在拥有的:

一个简单的视图模型

当我通过 @={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);
    }
}

片段中的简单布局:

<?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("This is the dashboard"),它工作正常并且值显示得很好。

在点击监听器dashBoardViewModel.onSave() 中,我可以调用text.setValue(newValue),它会分配正确的值,但该值永远不会显示。

所以text.setValue() 在同一个类/同一个实例中的工作方式似乎不同。

任何提示将不胜感激。

【问题讨论】:

    标签: java android two-way-binding


    【解决方案1】:

    您可能忘记将lifecycleowner 提供给您的databinding。你应该检查this one

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 2021-11-01
      相关资源
      最近更新 更多