1

I'm creating an adapter for a RecyclerView; currently creating an onClickListener to the items within the RecyclerView; I wish to go back to a fragment which I can't seem to do, so I have tried to add onBackPressed() with super.onBackPressed in the method as the fragment is on the previous page; I have called this in the onClickListener and it doesn't seem to work, any ideas how I can fix this?

Code is as follows:

public class MyViewHolder extends RecyclerView.ViewHolder { TextView text1, text2, text3;

public MyViewHolder(@NonNull View itemView) {
  super(itemView);
  itemView.setOnClickListener(new View.OnClickListener() {
    @Override public void onClick(View v) {
    // This onClick doesn't accept onBackPressed() or popBackStack(), however I need to get this to the previous page which is a fragment.
    }
  });
Kevin
  • 51
  • 6

1 Answers1

0

You need to pass an OnClickListener (or a custom callback interface) to the Adapter and that you pass on to every ViewHolder. Once the viewholder onClick is called, you call the passed listener which then bubbles up to the Fragment/Activity where you created your Adapter.

A good sample of that can be found in this answer: https://stackoverflow.com/a/28304164/180538

And of course you can call onBackPressed() in this passed onClickListener or whatever code you want to have executed there

WarrenFaith
  • 56,228
  • 24
  • 130
  • 145