RecyclerView ItemTouchHelper 拖动排序

RecyclerView ItemTouchHelper 踩坑之旅


要实现的功能:

  • recyclerview item适配器不同类型的Item addHeaderView
  • item headerview 不可以拖动交换位置

动手操作前先过一边原理 :站在大神的肩膀上看世界

谷歌大大这么说:

This is a utility class to add swipe to dismiss and drag & drop support to RecyclerView.

It works with a RecyclerView and a Callback class, which configures what type of interactions are enabled and also receives events when user performs these actions.
This class is designed to work with any LayoutManager but for certain situations, it can be optimized for your custom LayoutManager by extending methods in the ItemTouchHelper.Callback class or implementing ItemTouchHelper.ViewDropHandler interface in your LayoutManager.
  • RecylcerView Item拖动排序 滑动删除 依靠android.support.v7.widget.helper.ItemTouchHelper类
  • 自定义ItemTouchHelper.callBack 继承 getMoventFlags\onMove\onSwiped 方法

谷歌大大这么说

This class is the contract between ItemTouchHelper and your application. It lets you control which touch behaviors are enabled per each ViewHolder and also receive callbacks when user performs these actions.
To control which actions user can take on each view, you should override getMovementFlags(RecyclerView, ViewHolder) and return appropriate set of direction flags. (LEFT, RIGHT, START, END, UP, DOWN). You can use makeMovementFlags(int, int) to easily construct it. Alternatively, you can use ItemTouchHelper.SimpleCallback.
If user drags an item, ItemTouchHelper will call onMove(recyclerView, dragged, target). Upon receiving this callback, you should move the item from the old position (dragged.getAdapterPosition()) to new position (target.getAdapterPosition()) in your adapter and also call notifyItemMoved(int, int). To control where a View can be dropped, you can override canDropOver(RecyclerView, ViewHolder, ViewHolder). When a dragging View overlaps multiple other views, Callback chooses the closest View with which dragged View might have changed positions. Although this approach works for many use cases, if you have a custom LayoutManager, you can override chooseDropTarget(ViewHolder, java.util.List, int, int) to select a custom drop target.
When a View is swiped, ItemTouchHelper animates it until it goes out of bounds, then calls onSwiped(ViewHolder, int). At this point, you should update your adapter (e.g. remove the item) and call related Adapter#notify event.


public class MyRecyclerViewTouchCallBack extends ItemTouchHelper.Callback {
private ItemTouchListencer mListencer;

public MyRecyclerViewTouchCallBack(ItemTouchListencer listencer) {
    mListencer = listencer;
}

@Override
public boolean isLongPressDragEnabled() {
    return super.isLongPressDragEnabled();
}

@Override
public boolean isItemViewSwipeEnabled() {
    return super.isItemViewSwipeEnabled();
}

@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
    /*dragFlags--拖动标志*/
    /*swipeFlags--滑动标志 GridLayoutManager滑动删除关闭*/
    if (layoutManager instanceof GridLayoutManager) {
        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        final int swipeFlags = 0;
        return makeMovementFlags(dragFlags, swipeFlags);
    } else if (layoutManager instanceof LinearLayoutManager) {
        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
        return makeMovementFlags(dragFlags, swipeFlags);
    } else {
        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        final int swipeFlags = 0;
        return makeMovementFlags(dragFlags, swipeFlags);
    }
}


@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
    int startIndex = viewHolder.getAdapterPosition();
    int endIndex = target.getAdapterPosition();
    if (mListencer != null) {
        mListencer.itemMove(startIndex, endIndex);
    }
    return true;
}

@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
    if (mListencer != null) {
        mListencer.itemSwipe(direction);
    }
}

}

控制器 RecylerViewAdapter

public class ItemTouchRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ItemTouchListencer {

private static final int TYPE_HEADER_VIEW = 0;
private static final int TYPE_CONTENT = 1;
private ArrayList<String> mStrings;
private View mHeaderView;

public ItemTouchRecyclerViewAdapter(ArrayList<String> strings) {
    mStrings = strings;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == TYPE_HEADER_VIEW) {
        View view = View.inflate(parent.getContext(), R.layout.heander_view_item, null);
        return new HeaderViewHolder(view);
    } else if (viewType == TYPE_CONTENT) {
        View view = View.inflate(parent.getContext(), R.layout.gridview_item, null);
        return new GridViewHolder(view);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof GridViewHolder) {
        GridViewHolder gridViewHolder = (GridViewHolder) holder;
        String str = mStrings.get(position - 1);
        gridViewHolder.mTxt.setText(str);
    }else if(holder instanceof HeaderViewHolder){
        HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
    }
}

@Override
public int getItemCount() {
//        return mHeaderView != null ? mStrings.size() + 1 : mStrings.size();
    return mStrings.size();

}


@Override
public int getItemViewType(int position) {
    if (position == 0) {
        return TYPE_HEADER_VIEW;
    } else {
        return TYPE_CONTENT;
    }
}

/**
 * 拖动回调接口
 *
 * @param startIndex --开始位置
 * @param endIndex   --交换结束位置
 */
@Override
public void itemMove(int startIndex, int endIndex) {
    if (startIndex == 0 || endIndex == 0) {
        return;
    }
    Collections.swap(mStrings, startIndex, endIndex);
    notifyItemMoved(startIndex, endIndex);
}

/**
 * 滑动删除
 *
 * @param delIndex
 */
@Override
public void itemSwipe(int delIndex) {

}

}

调用初始化

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = 2;
                outRect.top = 2;
                outRect.bottom = 2;
            }
        });

        final GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return position == 0 ? gridLayoutManager.getSpanCount() : 1;
            }
        });
        mRecyclerView.setLayoutManager(gridLayoutManager);
        ArrayList<String> mStrings = new ArrayList<>();
        for (int i = 0; i < 18; i++) {
            mStrings.add("item  "+i);
        }
        ItemTouchRecyclerViewAdapter adapter = new ItemTouchRecyclerViewAdapter(mStrings);
        mRecyclerView.setAdapter(adapter);
        MyRecyclerViewTouchCallBack callBack= new MyRecyclerViewTouchCallBack(adapter);
        ItemTouchHelper touchHelper = new ItemTouchHelper(callBack);
        touchHelper.attachToRecyclerView(mRecyclerView);
    }
}
Screenshot_1495950511.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,711评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,079评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,194评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,089评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,197评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,306评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,338评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,119评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,541评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,846评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,014评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,694评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,322评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,026评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,257评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,863评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,895评论 2 351

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,914评论 25 707
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,417评论 2 45
  • 简介: 提供一个让有限的窗口变成一个大数据集的灵活视图。 术语表: Adapter:RecyclerView的子类...
    酷泡泡阅读 5,155评论 0 16
  • 这篇文章分三个部分,简单跟大家讲一下 RecyclerView 的常用方法与奇葩用法;工作原理与ListView比...
    LucasAdam阅读 4,381评论 0 27
  • 偶然的机会,一位未见面却感觉很亲切的姐姐,闲聊中提及到简书,立马很欢喜的加入进来。 原本我便十分喜爱写些摘文,从读...
    幽蓝_星空阅读 226评论 1 0