我正在实现Mvvm模型,并尝试使用MutableLiveData监听更改。
有两种方法
这是我正在尝试的代码,当我使用postValue时以及如果我使用setValue时都为null,它工作正常。
ViewModel
private MutableLiveData<List<Model>> modelsLiveData = new MutableLiveData<>();
public MainActivityViewModel() {
modelsLiveData = new MutableLiveData<>();
}
public MutableLiveData<List<Model>> getModelsLiveData() {
return modelsLiveData;
}
public void setModelsLiveData(final List<Model> modelsList) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i("LIVE_DATA_TEST", Thread.currentThread().toString());
Thread.sleep(1000);
modelsLiveData.postValue(modelsList);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
MainActivity
ActivityMainBinding activityBinding = DataBindingUtil
.setContentView(this, R.layout.activity_main, new AppDataBindingComponent<>(this));
MainActivityViewModel viewModel = new MainActivityViewModel();
activityBinding.setViewModel(viewModel);
Log.i("LIVE_DATA_TEST", "onCreate: "+ Thread.currentThread());
List<Model> modelsList = new ArrayList<>();
modelsList.add(new Model("Suzuki Swift", 2761111));
modelsList.add(new Model("Renoult Megan", 3679060));
modelsList.add(new Model("Fiat Panda", 4638764));
modelsList.add(new Model("Fiat 500", 1234567));
modelsList.add(new Model("Toyota Land Crouser", 9876543));
viewModel.setModelsLiveData(modelsList);
布局
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.matanmarciano.mvvmlivedata.viewmodels.MainActivityViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/models_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:items="@{viewModel.modelsLiveData}" />
</LinearLayout>
DataBindingAdapter
@BindingAdapter({"items"})
public void items(final RecyclerView recyclerView, List<Model> models) {
Log.i("LIVE_DATA_TEST", "Let's see if this method is reached" + models);
// TODO: update recyclerView adapter...
}
记录
这就是我得到的
I/LIVE_DATA_TEST: onCreate: Thread[main,5,main]
I/LIVE_DATA_TEST: Thread[Thread-4,5,main]
I/LIVE_DATA_TEST: Let's see if this method is reached null // null I am getting here when using postValue.
请帮我哪里做错了。
最佳答案
您必须添加setLifecycleOwner才能从数据绑定(bind)中订阅liveData。
ActivityMainBinding activityBinding = DataBindingUtil
.setContentView(this, R.layout.activity_main, new AppDataBindingComponent<>(this));
activityBinding.setLifecycleOwner(this);
https://developer.android.com/topic/libraries/data-binding/architecture#livedata
关于android - MutableLiveData的postValue方法返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57330624/