我有MainActivity,其中包含带有RecyclerAdapter1的RecyclerView1。 RecyclerView1中的ViewHolder包含另一个带有RecyclerAdapter2的RecyclerView2。
在RecyclerView2中有一个ImageView; ImageView上的onClick方法调用RecyclerView2的notifyDataSetChanged(),但不会刷新视图。
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDbHelper = new SkillManagerDatabaseHelper(this);
initializeDisplayContent();
}
private void initializeDisplayContent() {
RecyclerView recyclerCategories = findViewById(R.id.list_categories);
mCategoriesLayoutManager = new LinearLayoutManager(this);
mCategoryRecyclerAdapter = new CategoryRecyclerAdapter(this, mDbHelper.getAllCategories());
recyclerCategories.setLayoutManager(mCategoriesLayoutManager);
recyclerCategories.setAdapter(mCategoryRecyclerAdapter);
}
RecyclerView1:
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
CategoryInfo categoryInfo = mCategoriesList.get(position);
LinearLayoutManager tasksLayoutManager = new LinearLayoutManager(viewHolder.mHolderView.getContext());
mTaskRecyclerAdapter = new TaskRecyclerAdapter(viewHolder.mHolderView.getContext(), categoryInfo.getTasks());
RecyclerView recyclerTasks = viewHolder.mHolderView.findViewById(R.id.list_tasks);
recyclerTasks.setLayoutManager(tasksLayoutManager);
recyclerTasks.setAdapter(mTaskRecyclerAdapter);
}
RecyclerView2:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public final ImageView mCheckboxImage;
private SkillManagerDatabaseHelper mDbHelper;
public ViewHolder(@NonNull final View itemView) {
super(itemView);
mCheckboxImage = itemView.findViewById(R.id.checkbox_image);
mCheckboxImage.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == mCheckboxImage.getId()) {
int position = getAdapterPosition();
TaskInfo task = mTasksList.get(position);
int viewId = task.getTaskId();
onImageClick(viewId, position);
notifyDataSetChanged(); //call function inside ViewHolder - doesn't work
}
}
}
public void onImageClick(int taskId, int position) {
dBHelper.completeTask(taskId); //this function works, minimizing app and re-opening it shows correct data.
notifyDataSetChanged(); //call function outside of viewHolder class, directly in Adapter - doesn't work.
}