在 RecyclerView 适配器的 ViewHolder 中显示 AlertDialog class
Displaying an AlertDialog in ViewHolder in a RecyclerView Adapter class
我已经实现了一个包含一些行的 RecyclerView,我现在正尝试使用 AlertDialog 在用户点击一行时显示一条消息。
我已经在 Adapter 中成功实现了 setOnClickListener,但是我无法让 AlertDialog 工作,系统一直告诉我我不能在 ViewHolder 中使用 AlertDialog.Builder:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
我的 GitHub 代码是 here
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView;
itemView.setOnClickListener(this);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(null);
{
alertDialogBuilder
.setMessage("You selected ")
.setCancelable(true); // True allows you to use the back button to exit the dialog, false does not
}
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
今天和老公重构完毕,更新代码为here。
我们创建了一个接口并在主 activity 中实现了它,然后我们从 itemView 上的 View.OnClickListener 集调用了这个接口中的方法。
我们向 ViewHolder
添加一个点击监听器:
然后让 Activity
成为监听器:
希望这个问题对以后的其他人有所帮助。
只需使用
AlertDialog alertDialog = new AlertDialog.Builder(itemView.getParent().getContext());
您的问题将得到解决。