Displaying an AlertDialog in ViewHolder in a RecyclerView Adapter class

Lara Ruffle Coles picture Lara Ruffle Coles · Oct 30, 2015 · Viewed 9.2k times · Source

I've implemented a RecyclerView with some rows and I'm now trying to use AlertDialog to display a message when the user taps on a row.

I've successfully implemented the setOnClickListener in the Adapter but I can't get the AlertDialog to work, the system keeps telling me I can't use AlertDialog.Builder in a ViewHolder:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

My GitHub code is 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();
    }

Answer

Lara Ruffle Coles picture Lara Ruffle Coles · Nov 1, 2015

Ended up refactoring with the husband today, updated code is here.

We created an interface and implemented it in the main activity, we then called the method in this interface from a View.OnClickListener set on the itemView.

We add a click listener to the ViewHolder:

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

and then make the Activity the listener:

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

Hopefully this question might help someone else in the future.