要更改LiveData以更新RecyclerView,可以按照以下步骤进行:
下面是一个示例代码:
public class MyViewModel extends ViewModel {
private MutableLiveData<List<Item>> itemListLiveData = new MutableLiveData<>();
public LiveData<List<Item>> getItemListLiveData() {
return itemListLiveData;
}
public void updateItemList(List<Item> itemList) {
itemListLiveData.setValue(itemList);
}
}
public class MyActivity extends AppCompatActivity {
private MyViewModel viewModel;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
viewModel.getItemListLiveData().observe(this, new Observer<List<Item>>() {
@Override
public void onChanged(List<Item> itemList) {
adapter.updateItemList(itemList);
}
});
RecyclerView recyclerView = findViewById(R.id.recyclerView);
adapter = new MyAdapter();
recyclerView.setAdapter(adapter);
}
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Item> itemList = new ArrayList<>();
public void updateItemList(List<Item> itemList) {
this.itemList = itemList;
notifyDataSetChanged();
}
// 其他适配器相关的方法...
}
这样,当LiveData对象的值发生变化时,适配器会更新数据列表,并通知RecyclerView进行刷新。
领取专属 10元无门槛券
手把手带您无忧上云