Androidrecyclerview实现拖拽排序和侧滑删除-创新互联
Recyclerview现在基本已经替代Listview了,RecyclerView也越来越好用了 当我们有实现条目的拖拽排序和侧滑删除时 可以直接时候Recyclerview提供的API就可以直接实现了
先贴上主要代码
private void initveiw() { ArrayListitems = new ArrayList<>(Arrays.asList("itme1", "item2", "itme3", "item4", "item5", "item6", "item7", "item8", "itme9", "item10", "itme11", "item12", "item13", "item14", "item15", "item16")); recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)); SimpleAdapter adapter = new SimpleAdapter(items); recyclerView.setAdapter(adapter); ItemTouchHelper helper = new ItemTouchHelper(new MyItemTouchCallback(adapter)); helper.attachToRecyclerView(recyclerView); } public class MyItemTouchCallback extends ItemTouchHelper.Callback{ private SimpleAdapter adapter; public MyItemTouchCallback(SimpleAdapter adapter) { this.adapter = adapter; } @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { int dragFlag; int swipeFlag; RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager instanceof GridLayoutManager){ dragFlag = ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; swipeFlag = 0; }else{ dragFlag = ItemTouchHelper.DOWN | ItemTouchHelper.UP; swipeFlag = ItemTouchHelper.END | ItemTouchHelper.START; } return makeMovementFlags(dragFlag,swipeFlag); } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { int fromPosition = viewHolder.getAdapterPosition(); int toPosition = target.getAdapterPosition(); if (fromPosition < toPosition ){ for (int i = fromPosition ;i toPosition; i--){ Collections.swap(adapter.getDataList(),i ,i-1); } } recyclerView.getAdapter().notifyItemMoved(fromPosition,toPosition); return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { int position = viewHolder.getAdapterPosition(); if (direction == ItemTouchHelper.END | direction==ItemTouchHelper.START){ adapter.getDataList().remove(position); adapter.notifyItemRemoved(position); } } @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { super.onSelectedChanged(viewHolder, actionState); if (actionState==ItemTouchHelper.ACTION_STATE_DRAG){ viewHolder.itemView.setBackgroundColor(Color.BLUE); } } @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); viewHolder.itemView.setBackgroundColor(0); } }
分享名称:Androidrecyclerview实现拖拽排序和侧滑删除-创新互联
网页地址:http://scyanting.com/article/dseogc.html