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();
}
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
:
and then make the Activity
the listener:
Hopefully this question might help someone else in the future.