简体   繁体   中英

Android - exit activity on item click in recycler view

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?

Use the Following:

Declare context globally.

Context c;

Then type-cast context with your activity.

((YourActivity)c).finish();

Hope this helps.

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

Hope this Helps.

Sorry for my english.

您可以从flagNameTextView获取上下文:

((Activity)holder.flagNameTextView.getContext()).finish();  

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM