Get the position of clicked item on Recycler View

前端 未结 3 998
旧时难觅i
旧时难觅i 2021-01-15 17:57

I have implement a RecyclerView and it works fine. I have an ArrayList which contains the data for the recycler view. The layout of each item is co

3条回答
  •  星月不相逢
    2021-01-15 18:52

    Try this

    public class ClosetListAdapter extends RecyclerView.Adapter {
        ClosetListAdapter (CallBack callback){
           this.callback = callback
        }
    
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder baseholder, int position) {
            ViewHolder holder = (ViewHolder) baseholder;
            holder.setPosition(position);
            holder.name.setText(product.getName());
        }
    
        static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
            public TextView name = null;
    
            private OnProductClickListener onProductClickListener;
    
            public ViewHolder(View itemView, OnProductClickListener onClickListener) {
                super(itemView);
    
                name = (TextView) itemView.findViewById(R.id.item_name);
                itemView.setOnClickListener(this)
    
            }
    
            public void setProdcut(Product product) {
                this.product = product;
            }
    
            @Override
            public void onClick(View v) {
                if (callback!= null) {
                    callback.itemClicked(pos);
                }
            }
    
            public void setPosition(int position){
                this.pos = position;
            }
        }
    
        interface CallBack {
           void itemClicked(int position);
        }
    }
    

提交回复
热议问题