Android-RecyclerView: handle item click event

One way to handle Item click event while using RecyclerView is to specify the handler inside the constructor of the ViewHolder inside the Adapter class.

Like this:

/*Adapter class*/
private class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder>{ //item = ViewHolder type
    private List<Country> countryData;
    private Context context;
    /*Constructor of the adapter class*/
    public MyRecyclerAdapter (List<Country> data,Context context){
        this.context = context;
        this.countryData = data;
    }

    /*ViewHolder*/
    public class ViewHolder extends RecyclerView.ViewHolder /*implements View.OnClickListener*/{
        public TextView tvName;
        public TextView tvRank;
        public TextView tvPop;
        public ImageView ivFlag;
        View itemCountry;

        /*Constructor of the ViewHolder*/
        public ViewHolder(View itemCountry){
            super(itemCountry);
            tvName =(TextView) itemCountry.findViewById(R.id.name_cfrag);
            tvRank = (TextView) itemCountry.findViewById(R.id.rank_cfrag) ;
            tvPop = (TextView) itemCountry.findViewById(R.id.population_cfrag);
            ivFlag = (ImageView) itemCountry.findViewById(R.id.flag_cfrag);
        /*HERE: Event handler*/
            itemCountry.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                         /*TODO: Do what you want here*/
                }
            });
        }
    }

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s