0

I've got a bunch of list items in my RecyclerView. I am handling the clicks properly for each item, but I need to close the activity when any item is clicked. Becuase RecyclerView doesn't have setOnItemClickListener method, I have to do this within the adapter:

@Override
public void onBindViewHolder(final Holder holder, int position) {
    // ...

    holder.flagNameTextView.setText(arrayList.get(position).getName());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Go back to the previous activity
            // such as onBackPressed();
        }
    });
}

But of course, the adapter is not extending the Activity, so I can't use onBackPressed() or finish().

How can I do this?

busuu
  • 586
  • 9
  • 22
  • Possible duplicate of [Calling activity from ViewHolder in RecyclerView?](http://stackoverflow.com/questions/25688620/calling-activity-from-viewholder-in-recyclerview) – OneCricketeer Mar 05 '17 at 18:59
  • @Prajnan Bhuyan Yes, but like I said in the question, I can't use the `finish()` method because the click is within the adapter which is NOT extending `Activity` class. – busuu Mar 05 '17 at 18:59
  • Pass the context object in the constructor of the Adapter and call context.finish() wherever you want your activity to be finished [See this](http://stackoverflow.com/q/32136973/681929) – nobalG Mar 05 '17 at 19:00
  • @Prajan You cannot call finish from an Adapter class @ Milan You need to "extract" the click event from the Adapter and set it from the Activity... and that's been addressed several places – OneCricketeer Mar 05 '17 at 19:00

5 Answers5

2

Use the Following:

Declare context globally.

Context c;

Then type-cast context with your activity.

((YourActivity)c).finish();

Hope this helps.

tahsinRupam
  • 6,325
  • 1
  • 18
  • 34
1

You can pass a reference of your activity throw the adapter constructor and call Activity.finish();

Hope this Helps.

Sorry for my english.

Cochi
  • 2,199
  • 2
  • 12
  • 15
0

You can get the context from the flagNameTextView :

((Activity)holder.flagNameTextView.getContext()).finish();  
Nika Kurdadze
  • 2,502
  • 4
  • 18
  • 28
0

Besides, you can define a interface callback like OnClickListener in RecyclerView adapter. Then Implement this interface in Activity, pass it into the adapter and then use it in View's OnClickListner callback.

Jack_Zhang
  • 11
  • 3
-1

Just use YourActivityName.this.finish().

By adding the Activity name you are telling android which "this" you want.

This will only work if your adapter is NOT defined as a static class.

theblitz
  • 6,683
  • 16
  • 60
  • 114