在一个片段中,我将参数diaryViewModel称为onActivityCreated()中的日期:
mDiaryViewModel = ViewModelProviders.of(this, new MyViewModelFactory(this.getActivity().getApplication(), date)).get(DiaryViewModel.class);
此外,我有一个textview,其当前日期位于两个箭头之间的layout(fragment)的顶部。左箭头表示单击该日期后,当前日期将变为负一天,而另一箭头为一天。基于更改的日期,我也希望实时数据(回收者视图)也更改。这是称为onActivityCreated()的代码,我在箭头的onClick方法中插入了相同的代码。
mDiaryViewModel = ViewModelProviders.of(this, new MyViewModelFactory(this.getActivity().getApplication(), date)).get(DiaryViewModel.class);
mDiaryViewModel.getTodayEntries(date).observe(this, new Observer<List<Diary>>() {
@Override
public void onChanged(@Nullable final List<Diary> diary) {
// Update the cached copy of the words in the adapter.
adapter.setDiary(diary);
}
});
适配器代码:
public class DiaryListAdapter extends RecyclerView.Adapter<DiaryListAdapter.DiaryViewHolder> {
class DiaryViewHolder extends RecyclerView.ViewHolder {
private final TextView timeItemView;
private final TextView foodNameItemView;
private final TextView gramsItemView;
private DiaryViewHolder(View itemView) {
super(itemView);
timeItemView = itemView.findViewById(R.id.time);
foodNameItemView = itemView.findViewById(R.id.f_name);
gramsItemView = itemView.findViewById(R.id.f_grams);
}
}
private final LayoutInflater mInflater;
private List<Diary> mDiary; // Cached copy of user
DiaryListAdapter(Context context) { mInflater = LayoutInflater.from(context); }
@Override
public DiaryListAdapter.DiaryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.recyclerview_diary, parent, false);
return new DiaryListAdapter.DiaryViewHolder(itemView);
}
@Override
public void onBindViewHolder(DiaryListAdapter.DiaryViewHolder holder, int position) {
if (mDiary != null) {
Diary current = mDiary.get(position);
holder.timeItemView.setText(String.valueOf(current.getTime()));
holder.foodNameItemView.setText(current.getFoodName());
holder.gramsItemView.setText(String.valueOf(current.getGrams()));
} else {
// Covers the case of data not being ready yet.
holder.foodNameItemView.setText("No User");
}
}
void setDiary(List<Diary> diaries){
mDiary = diaries;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't return null).
@Override
public int getItemCount() {
if (mDiary != null)
return mDiary.size();
else return 0;
}
}
以下是屏幕的原型,可为您提供更多帮助: prototype
答案 0 :(得分:0)
更新数据后,调用adapter.notifyDataSetChanged()方法。这将更新数据
mDiaryViewModel = ViewModelProviders.of(this, new MyViewModelFactory(this.getActivity().getApplication(), date)).get(DiaryViewModel.class);
mDiaryViewModel.getTodayEntries(date).observe(this, new Observer<List<Diary>>() {
@Override
public void onChanged(@Nullable final List<Diary> diary) {
// Update the cached copy of the words in the adapter.
adapter.setDiary(diary);
// This will refresh the data
**adapter.notifyDatasetChanged()**
}
});
让我知道刷新数据是否不是问题