在 RecyclerView 中按下后退按钮恢复滑动视图?

Restore a swiped view on pressing back button in RecyclerView?

您好,我正在学习本教程 here 关于使用 itemtouchhelper.callback 在 RecyclerView 上拖动和滑动的内容 一切正常,但如果想恢复按后退按钮刷出的视图怎么办。怎么办?

您可以在单击后退按钮时存储要恢复的项目。如果对象为 null,则调用 super 方法,否则,将项目添加到适配器中。

您需要创建一个简单的界面来获取滑动的项目。

在适配器中:

private OnSwipeListener onSwipeListener;

@Override
public void onItemDismiss(int position) {
    if (onSwipeListener != null){
      onSwipeListener.onSwipeItem(data.get(position).clone());
    }
    data.remove(position);
    notifyItemRemoved(position);
}

中activity:

T itemSwiped;

// Somewhere after you have created the adapter
adapter.setOnSwipeListener(new OnSwipeListener(){
   @Override
   public void onSwipeItem(T item){
     itemSwiped = item;
   }
});
...
Override
public void onBackPressed() {
    if (itemSwiped == null){ 
      super.onBackPressed()
    } else {
      adapter.addItem(itemSwiped);
    }
}