RecyclerView 获取item,删除item的坑

场景:点击子布局中的imageview替换其图片,可以对imageview进行点击事件监听,也可以用一种更优雅的方式获取item,且使用简单。

获取item

自定义ViewHolder

public class ViewHolder extends RecyclerView.ViewHolder {
    private Context mContext;
    private View mItemView;
    private SparseArray mViews;
    public ViewHolder(View itemView) {
        super(itemView);
        mViews=new SparseArray<>();
        mItemView=itemView;
        mItemView.setTag(this);
    }
    public static ViewHolder getHolder(Context context, View itemview,ViewGroup parent,int layoutid){
        if (itemview==null){
            itemview= LayoutInflater.from(context).inflate(layoutid,parent,false);
            return new ViewHolder(itemview);
        }else {
            ViewHolder vh= (ViewHolder) itemview.getTag();
            return vh;
        }
    }
    public  T getView(int id){
        View view=mViews.get(id);
        if (view==null){
            view=mItemView.findViewById(id);
            mViews.put(id,view);
        }
        return (T) view;
    }
    public void setImageRes(int id,int res){
        ImageView img= (ImageView) mItemView.findViewById(id);
        img.setImageResource(res);
    }
    public void setText(int id,String str){
        TextView tv= (TextView) mItemView.findViewById(id);
        tv.setText(str);
    }
    public void setOnClick(int id, View.OnClickListener onClickListener){
        mItemView.findViewById(id).setOnClickListener(onClickListener);
    }
}
  • 1

使用

    @Override
    public CViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return CViewHolder.getHolder(parent.getContext(), null, parent, R.layout.item_collection);
    }

    @Override
    public void onBindViewHolder(final CViewHolder holder, final int position) {
        holder.setImageRes(R.id.iv_item_collectionimg, mModels.get(position).getImgres());
        holder.setText(R.id.tv_item_collectiongdes,mModels.get(position).getDes());
}
  • 1

删除item坑

 mModels.remove(i);
 notifyItemRemoved(i);
 //必须调用这行代码
 notifyItemRangeChanged(i, mModels.size());
  • 1

你可能感兴趣的:(android)