Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

RecyclerView 获取item,删除item的坑

$
0
0

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

获取item

自定义ViewHolder

public class ViewHolder extends RecyclerView.ViewHolder {
    private Context mContext;
    private View mItemView;
    private SparseArray<View> 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 extends View> 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);
    }
}

使用

    @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());
}

删除item坑

 mModels.remove(i);
 notifyItemRemoved(i);
 //必须调用这行代码
 notifyItemRangeChanged(i, mModels.size());
作者:danfengw 发表于2017/3/7 15:11:32 原文链接
阅读:49 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>