1. 程式人生 > >recycleview增加刪除

recycleview增加刪除

.activity

//點選條目刪除
ma.setOnItemClickListener(new MAdapter.OnItemClickListener() {
    @Override
    public void onItemClick(int position) {
        ma.remove(position);
    }

    @Override
    public void onItemLongClick(int position) {
        ma.add(position);
    }
});
//點選按鈕刪除
case R.id.btn_add:
    ma.add(0);
    break;
case R.id.btn_delete:
    ma.remove(0);
    break;

.MAdapter

//介面回撥,刪除
public interface OnItemClickListener{
    void onItemClick(int position);
    void onItemLongClick(int position);
}

public OnItemClickListener mOnItemClickListener;

public void setOnItemClickListener(OnItemClickListener onItemClickListener){
    mOnItemClickListener = onItemClickListener;
}

public void add(int i) {
    list.add(i,list.get(i+1));
    Toast.makeText(mainActivity, "新增成功", Toast.LENGTH_SHORT).show();
    notifyItemInserted(i);
    notifyDataSetChanged();
}

public void remove(int i) {
    list.remove(i);
    Toast.makeText(mainActivity, "刪除成功", Toast.LENGTH_SHORT).show();
    notifyItemRemoved(i);
    notifyDataSetChanged();
}

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
    ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(),holder.iv);
    holder.tv1.setText(list.get(position).getTitle());
    holder.tv2.setText(list.get(position).getDate());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int layoutPosition = holder.getLayoutPosition();
            mOnItemClickListener.onItemClick(layoutPosition);
        }
    });

    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            int layoutPosition = holder.getLayoutPosition();
            mOnItemClickListener.onItemLongClick(layoutPosition);
            return false;
        }
    });
}