7

首先,我整天都在做这件事,但什么都做不了。我有一个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它隐藏视图的其余部分并显示带有撤消按钮的界面。但是,直到我将视图滚动出去并再次滚动回来,这种情况才会发生。有什么建议我缺少什么吗?

问题案例

链接

适配器类 ViewHolder 类

4

2 回答 2

4

终于让它运行起来了。由于notifyItemChanged没有切割它(它应该有),我使用notifyItemRemoved后跟notifyItemInserted.

滞后一点但有效。

于 2016-08-18T20:05:23.143 回答
3

我创建了一个简单的示例 Android 应用程序来更好地理解这个问题。

它利用notifyItemChanged(position); 当用户向左或向右滑动项目以显示撤消视图时。当撤消时间到期时,它调用notifyItemRemoved(position)将其从列表中删除。例如,请参见 GIF,不会留下任何空行。

https://github.com/DawidvanGraan/ExampleRecycleViewSwipeDismiss

于 2016-08-18T14:54:51.950 回答