[java]如何在片段中正确设置回收器视图
· 收录于 2023-09-24 05:29:11 · source URL
问题详情
我想知道我应该如何在我的片段中正确设置我的回收器视图,dashboardViewModel 观察文本字段,但我还没有找到如何观察回收器视图,所以我只是绑定它并设置了一个适配器,但我认为我的方式错了。
// My Dashboard fragment :
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
DashboardViewModel dashboardViewModel =
new ViewModelProvider(this).get(DashboardViewModel.class);
binding = FragmentDashboardBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textDashboard;
dashboardViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
RecyclerView recyclerView = binding.recyclerView;
DummyDatas dummyDatas = new DummyDatas();
ProductAdapter productAdapter = new ProductAdapter(dummyDatas.getProducts());
recyclerView.setAdapter(productAdapter);
return root;
// My Dash board view Model
public DashboardViewModel() {
mText = new MutableLiveData<>();
mProducts = new MutableLiveData<>();
DummyDatas dummyDatas = new DummyDatas();
List<Product> products = dummyDatas.getProducts();
double totalBasketPrice = 0.0;
for (Product product : products){
System.out.println(product.getPriceAtUnit());
totalBasketPrice = totalBasketPrice + product.getPriceAtUnit();
}
mProducts.setValue(products);
mText.setValue("Price :" + totalBasketPrice);
}
public LiveData<String> getText() {
return mText;
}
public LiveData<List<Product>> getProducts() {
return mProducts;
}
}
最佳回答
您可以使用 LiveData.observe()
函数中的适配器更新 RecyclerView 数据。
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
DashboardViewModel dashboardViewModel =
new ViewModelProvider(this).get(DashboardViewModel.class);
binding = FragmentDashboardBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textDashboard;
dashboardViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
RecyclerView recyclerView = binding.recyclerView;
DummyDatas dummyDatas = new DummyDatas();
final ProductAdapter productAdapter = new ProductAdapter(dummyDatas.getProducts());
recyclerView.setAdapter(productAdapter);
// observe products and update data using adapter's data functions
// either replace the whole list, or use DiffUtil
dashboardViewModel.getProducts().observe(getViewLifecycleOwner(), products -> {
productAdapter.setProducts(products);
productAdapter.notifyDataSetChanged();
});
return root;
}