RecyclerView
中有AdapterActivity
。点击任何项目后,我使用AlertDialogShow#UpdateStudent()
方法更新该项目。我的问题是我无法使用Adapter
刷新UpdateStudent()
方法中的notifyItemChanged()
。
如何从另一个无法直接访问Adapter
的课程中刷新Adapter
?
AdapterActivity
与RecyclerView
:
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;
}
}
答案 0 :(得分:0)
更新RecyclerView
适配器只能在适配器本身或Activity
中的适配器实例中完成。要达到这些方法,您需要使用如下界面:
public class AlertDialogShow {
public interface OnItemChange {
void notifyAdapter(int position);
}
private OnItemChange listener;
public AlertDialogShow(...) {
this.listener = (MyActivity)context;
}
}
然后在Activity
中编写OnItemChange接口的实现,如下所示:
public class MyActivity extends ... implements AlertDialogShow.OnItemChange {
@Override
public void notifyAdapter(int position) {
// Notify your adapter item change here
// e.g.: adapter.notifyItemChanged(position);
}
}
然后您可以在OnItemChange
类中使用AlertDialogShow
侦听器,如下所示:
this.listener.notifyAdapter(position);
这会在notifyAdapter(int position)
中调用Activity
方法并执行您在那里编写的代码。