首先,我整天都在努力,但无法完成任何事情。我有RecyclerView
一个使用RecyclerView
' s SortedList
的适配器。我尝试使用回调类实现TouchHelper
:
public class TimerListTouchHelperCallback extends ItemTouchHelper.SimpleCallback {
private OnItemChangeListener onItemChangeListener;
public TimerListTouchHelperCallback(OnItemChangeListener listener, int dragDirs, int swipeDirs) {
super(dragDirs, swipeDirs);
this.onItemChangeListener = listener;
}
@Override
public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
TimerHolder holder = (TimerHolder) viewHolder;
int holderState = holder.getState();
if (holderState == TimerHolder.TIMER_PENDING_DELETE) return 0;
else return super.getSwipeDirs(recyclerView, viewHolder);
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
TimerHolder holder = (TimerHolder) viewHolder;
int position = holder.getAdapterPosition();
// ViewHolder's state is changed that should handle the layout change.
holder.setState(TimerHolder.TIMER_PENDING_DELETE);
if (onItemChangeListener != null) onItemChangeListener.onItemSwiped(position);
}
protected interface OnItemChangeListener{
void onItemSwiped(int position);
}
}
这是TouchHelper的初始化
timerAdapter = new TimerAdapter(this, timerList);
timerListView.setAdapter(timerAdapter);
TimerListTouchHelperCallback touchHelperCallback = new TimerListTouchHelperCallback(
timerAdapter,
ItemTouchHelper.LEFT,
ItemTouchHelper.LEFT);
ItemTouchHelper swipeToDismissTouchHelper = new ItemTouchHelper(touchHelperCallback);
swipeToDismissTouchHelper.attachToRecyclerView(timerListView);
我的适配器实现了接口OnItemChangeListener
@Override
public void onItemSwiped(int position) {
notifyItemChanged(position);
removalPendingTimers.add(timerList.get(position));
}
我的ViewHolder
读取状态,当状态为TimerHolder.TIMER_PENDING_DELETE
时,它会隐藏视图的其余部分并显示带有撤消按钮的界面。但是直到我滚动视图并再次向后滚动它才会发生这种情况。有什么建议我缺少什么吗?
链接
答案 0 :(得分:3)
终于让它运行了。由于notifyItemRemoved
没有削减它(它应该有),我使用notifyItemInserted
后跟{{1}}。
稍微停滞一下但是有效。
答案 1 :(得分:1)
我已经创建了一个简单的Android应用示例来更好地理解这个问题。
当用户向左或向右滑动项目以显示撤消视图时,它会使用 notifyItemChanged(position); 。当撤消时间到期时,它会调用 notifyItemRemoved(position)将其从列表中删除。例如,请参阅GIF,不要留下任何空行。
https://github.com/DawidvanGraan/ExampleRecycleViewSwipeDismiss