Androidx滑动以在回收器视图中显示删除图标,然后进一步滑动以删除

时间:2019-08-09 07:52:31

标签: android android-recyclerview swipe androidx itemtouchhelper

我实现了向左滑动以在回收器视图中删除操作,如下所示:

ItemTouchHelper

public class SwipeToDelete extends ItemTouchHelper.SimpleCallback {

    //my custom adapter
    private MyAdapter slAdapter;

    public SwipeToDelete(MyAdapter adapter){
       // TO only swipe to the left
        super(0, ItemTouchHelper.LEFT);
        slAdapter = adapter;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        int position = viewHolder.getAdapterPosition();
        slAdapter.deleteItem(position);
    }
}

MyAdapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MYViewHolder> {

   //... onCreateViewHolder .. etc

   //creating a list of my custom layout view
   private List<MyCustomCardView> cards;

   public void deleteItem(int position){
        cards.remove(position);
        notifyItemRemoved(position);
    }
}

有了这些,我就能在recyclerView中滑动和删除视图。

我想做的是中途停止滑动并显示一个图标。然后,用户可以单击该图标,然后继续滑动并删除该视图,或者亲自继续滑动并删除该视图。

现在,用户仅需向左滑动即可自动继续滑动,我想执行一个中间步骤,该步骤显示可单击的图标。上面的代码如何做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以在模型中使用额外的布尔字段(例如:isShowRemoveButton),而不是将“ cards.remove(position)”设置为true(例如:cards.get(position).setShowRemoveButton(true)),然后在您的模型中onBindViewHolder处理它可以在项目布局上显示删除按钮

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MYViewHolder> {

       //... onCreateViewHolder .. etc

    private List<MyCustomCardData> cards;//CardData instead of CardView

    public void deleteItem(int position){
            cards.get(position).setShowRemoveButton(true) ;
            notifyItemRemoved(position);
        }

    public void onBindViewHolder(myViewHolder holder, int position) {

            MyCustomCardData currentdata = cards.get(position);
            holder.removeButton.setVisibility(currentdata.isShowRemoveButton? VISIBLE : GONE);
    }
}