0

I have a RecyclerView which for each item contains a button. I want to handle the click event for this button in the activity holding the RecyclerView instead of inside the adapter as I have heard this is the best approach.

Here is my adapter class:

public class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.ViewHolder> {

    private List<User> results;

    public SearchResultAdapter(List<User> results) {
        this.results = results;
    }

    @Override
    public SearchResultAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_search_results_recycler_view, parent, false);
        return new SearchResultAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(SearchResultAdapter.ViewHolder holder, int position) {
        String fullName = results.get(position).getFirstName() +
                " " + results.get(position).getLastName();
        holder.mFullNameTextView.setText(fullName);
    }

    @Override
    public int getItemCount() {
        return results.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.search_full_name_text_view)
        TextView mFullNameTextView;

        @BindView(R.id.send_request_button)
        Button mSendRequestButton;

        ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}

How should I handle the click event of the mSendRequestButton with the corresponding User object from the results list to the activity? I can think of using an interface but maybe there is a cleaner way.

Tom Finet
  • 2,056
  • 6
  • 30
  • 54

0 Answers0