在RecyclerView Adapter类的ViewHolder中显示AlertDialog

Lar*_*les 4 android android-alertdialog android-viewholder

我已经实现了一些带有一些行的RecyclerView,现在我正在尝试使用AlertDialog在用户点击一行时显示一条消息.

我已经在Adapter中成功实现了setOnClickListener但是我无法使AlertDialog工作,系统一直告诉我我不能在ViewHolder中使用AlertDialog.Builder:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
Run Code Online (Sandbox Code Playgroud)

我的GitHub代码就在这里

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();
    }
Run Code Online (Sandbox Code Playgroud)

Lar*_*les 5

今天结束了与丈夫的重构,更新的代码在这里.

我们创建了一个接口并在main活动中实现它,然后我们从itemView上设置的View.OnClickListener调用此接口中的方法.

我们在以下位置添加了一个点击监听器ViewHolder:

https://github.com/lararufflecoles/RecyclerView100/blob/master/app/src/main/java/es/rufflecol/lara/recyclerview100/RecyclerAdapter.java#L69

然后成为Activity听众:

https://github.com/lararufflecoles/RecyclerView100/blob/master/app/src/main/java/es/rufflecol/lara/recyclerview100/MainActivity.java#L42

希望这个问题可能在将来帮助其他人.