要创建一个Android独立的RecyclerView适配器的ViewModel,您可以按照以下步骤进行操作:
MyAdapterViewModel
的类。public class MyAdapterViewModel extends ViewModel {
private MutableLiveData> mDataList = new MutableLiveData<>();
public LiveData> getDataList() {
return mDataList;
}
public void setDataList(List dataList) {
mDataList.setValue(dataList);
}
}
public class MyFragment extends Fragment {
private MyAdapter mAdapter;
private MyAdapterViewModel mViewModel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 实例化ViewModel对象
mViewModel = ViewModelProviders.of(this).get(MyAdapterViewModel.class);
// 创建并设置适配器
mAdapter = new MyAdapter();
// 观察ViewModel中的数据变化,并将其传递给适配器
mViewModel.getDataList().observe(this, new Observer>() {
@Override
public void onChanged(@Nullable List dataList) {
mAdapter.setData(dataList);
}
});
}
}
public class MyAdapter extends RecyclerView.Adapter {
private List mDataList;
public void setData(List dataList) {
mDataList = dataList;
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// 创建ViewHolder并返回
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// 绑定数据到ViewHolder中的视图
}
@Override
public int getItemCount() {
return mDataList != null ? mDataList.size() : 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// ViewHolder中的视图定义
}
}
通过上述步骤,您可以创建一个Android独立的RecyclerView适配器的ViewModel,并在其中处理数据和逻辑,使您的代码更具可维护性和可扩展性。