android之RecycleView适配器添加点击事件

public class RecycleAdapter extends RecyclerView.Adapter {
    private List mData;
    public OnItemClickListener itemClickListener;

    public interface  OnItemClickListener{
        void onItemClick(View view,int position);
    }

    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public RecycleAdapter(List mData){
        this.mData=mData;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //将布局转化为View并传递给RecycleView封装好的ViewHolder
        View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycle,parent,false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        //建立起ViewHolder中视图与数据的关联
        holder.textView.setText(mData.get(position)+position);
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView textView;


        public ViewHolder(View itemView){
            super(itemView);
            textView= itemView.findViewById(R.id.tv_content);
            textView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (itemClickListener!=null){
                itemClickListener.onItemClick(view,getPosition());
            }
        }
    }
}
mAdapter.setOnItemClickListener(new RecycleAdapter.OnItemClickListener() {
     @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
     @Override
     public void onItemClick(final View view, int position) {
           //设置点击动画
           Toast.makeText(RecycleViewActivity.this,
                 mData.get(position)+position+"",Toast.LENGTH_SHORT).show();
     }
});

 

你可能感兴趣的:(android)