gpt4 book ai didi

android - 从另一个类调用 RecyclerView.Adapter 上的 notifyItemChanged()

转载 作者:太空狗 更新时间:2023-10-29 14:40:02 27 4
gpt4 key购买 nike

我在 AdapterActivity 中有一个 RecyclerView。单击其任何项目后,我使用 AlertDialogShow#UpdateStudent() 方法更新该项目。我的问题是我无法使用 notifyItemChanged() 刷新 UpdateStudent() 方法内的 Adapter

如何从无法直接访问 Adapter 的另一个类刷新 Adapter

在带有 RecyclerViewAdapterActivity 中:

holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialogShow show =
new AlertDialogShow(context, database, studentData, performanceData);
show.UpdateStudent(studentName, studentId, classId, position);
}
}
}

AlertDialogShow 类:

public class AlertDialogShow {

Context context;
DatabaseHandler database;
List<StudentTable> studentData;

public AlertDialogShow(Context context, DatabaseHandler database,
List<StudentTable> studentData , List<PerformanceTable> performanceData) {
this.context = context;
this.database = database;
this.studentData = studentData;
this.performanceData = performanceData;
}

public AlertDialog UpdateStudent(final String studentName, final String studentId,
final int classId , final int position) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
View viewLayout = LayoutInflater.from(context)
.inflate(R.layout.alertdialog_edit_class_or_student , null);
dialog.setView(viewLayout);

final AlertDialog alertDialog = dialog.create();

Button editStudent_btn = (Button)viewLayout.findViewById(R.id.item_btn_EditClassStudent_Edit);

editStudent_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
database.UpdateStudentDatabase(classId , studentId_new , studentId, studentName_new);

StudentTable studentTable = studentData.get(position);
studentTable.setStudentName(studentName_new);
studentTable.setStudentId(studentId_new);
studentData.set(position , studentTable);
//notifyItemChanged(position); <-- cannot define this line
}
}
);

return alertDialog;
}
}

最佳答案

更新 RecyclerView 适配器只能在适配器本身或通过 Activity 中的适配器实例完成。要访问这些方法,您需要使用如下接口(interface):

public class AlertDialogShow {

public interface OnItemChange {
void notifyAdapter(int position);
}

private OnItemChange listener;

public AlertDialogShow(...) {
this.listener = (MyActivity)context;
}
}

然后在您的 Activity 中为 OnItemChange 接口(interface)编写一个实现,如下所示:

public class MyActivity extends ... implements AlertDialogShow.OnItemChange {

@Override
public void notifyAdapter(int position) {
// Notify your adapter item change here
// e.g.: adapter.notifyItemChanged(position);
}
}

然后您可以在您的 AlertDialogShow 类中使用 OnItemChange 监听器,如下所示:

this.listener.notifyAdapter(position);

这将调用 Activity 中的 notifyAdapter(int position) 方法并执行您在那里编写的代码。


祝你好运。

关于android - 从另一个类调用 RecyclerView.Adapter 上的 notifyItemChanged(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49708825/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com