Best place to attach onClickListener in recyclerview

对着背影说爱祢 提交于 2020-01-02 04:21:04

问题


While i was looking at some tutorials about recycler view.some of them used the viewHolder constructor to attach the onClick listener while some of them used the onBindViewHolder method. which method is the best place to attach the onclicklistener. i'm really confused


回答1:


The method onBindViewHolder is called every time when you bind your view with data. So there is not the best place to set click listener. You don't have to set OnClickListener many times for the one View. So the best solution is to set click listener in onCreateViewHolder method. But the important thing is a how do you implement on click listener. If you for example want to get some model from list you can use getAdapterPosition() method from ViewHolder.

Look at the exmaple

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

    final View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.view_magazine_list_item, null);

    final ViewHolder result = new ViewHolder(view);
    view.setOnClickListener(new OnClickListener(){
          @Override
          public void onClick(View v){
             YourObject yourobject = yourObjectsList.get(result.getAdapterPosition()));
          }
    });
    return result;
}



回答2:


In ViewHolder is the better place:

public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    //views declare here

    public ItemViewHolder(View convertView)
    {
        super(convertView);

        ... ...

        convertView.setOnClickListener(this);
    }



    @Override
    public void onClick(View v)
    {
       //do something to view here
           //also you can get view position by 'getPosition()' here     

    }


}



回答3:


Best practice to use the onClickListener inside the ViewHolder class of the Recyclview like below:-

public class ViewHolder extends RecyclerView.ViewHolder{    
        private View YOUR_VIEW;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            YOUR_VIEW = itemView.findViewById(R.id.YOUR_VIEW);

            YOUR_VIEW.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(mContext,"Position==>> "+getAdapterPosition(),Toast.LENGTH_LONG).show();

                }
            });
    }
}


来源:https://stackoverflow.com/questions/28904479/best-place-to-attach-onclicklistener-in-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!