Android开发Android开发经验谈Android技术知识

ItemTouchHelper.callback用法

2019-10-08  本文已影响0人  Ad大成

写一个接口 适配器实现接口 给接口定义的形参赋值
写一个类继承ItemTouchHelper 设置上下左右移动替换删除
然后在用到的界面关联
接口


public interface ItemTouchHelpAdapter {
    //定义移动方法
    void itemMove(int fromPosition,int toPosition);
    //定义移除方法
    void itemDelete(int position);
}

适配器


    @Override
    public void itemMove(int fromPosition, int toPosition) {
        Collections.swap(mDatas,fromPosition,toPosition);
        notifyItemMoved(fromPosition,toPosition);

    }

    @Override
    public void itemDelete(int position) {

        mDatas.remove(position);
        notifyItemRemoved(position);

    }

自定义类

public class MyItemTouchHelp extends ItemTouchHelper.Callback {

    private SelectorAdapter selectorAdapter;

    public MyItemTouchHelp(SelectorAdapter selectorAdapter) {
        this.selectorAdapter = selectorAdapter;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;        //允许上下的拖动
        int swipeFlags = ItemTouchHelper.LEFT;   //只允许从右向左侧滑
        return makeMovementFlags(dragFlags,swipeFlags);


    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                          RecyclerView.ViewHolder target) {
        selectorAdapter.itemMove(viewHolder.getAdapterPosition(),target.getAdapterPosition());
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        selectorAdapter.itemDelete(viewHolder.getAdapterPosition());
    }
}

应用

//        构建自定义类对象来多态创建ItemTouchHelper.Callback对象
        ItemTouchHelper.Callback  callback = new MyItemTouchHelp(selectorAdapter);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);

        itemTouchHelper.attachToRecyclerView(recycJuejin);
上一篇下一篇

猜你喜欢

热点阅读