RecyclerView实现Item条目随意拖拽排序
程序员文章站
2022-02-14 11:20:47
...
本文主要介绍一个RecyclerView的拖动排序的功能、实现了类似ListView的拖动和GridView的拖动排序、如果你还在使用ListView的话、可以放弃掉ListView了
因为RecyclerView自动帮我们缓存Item视图(ViewHolder)、允许我们自定义各种动作的动画和分割线、允许我们对Item进行一些手势操作、另外因为Design库的推出大大方便我们编写带有Material风格的App、而ListView是不兼容这个库的、比如滑动的相互协调、只有RecyclerView能做到、话不多说、先来看看Demo的效果图
onCreate初始化代码
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //////////////////////////////////////////////////////// /////////初始化数据,如果缓存中有就使用缓存中的 ArrayList<Item> items = (ArrayList<Item>) ACache.get(getActivity()).getAsObject("items"); if (items!=null) results.addAll(items); else { for (int i = 0; i < 3; i ) { results.add(new Item(i*8 0,"美食", R.drawable.ic_category_0)); results.add(new Item(i*8 1,"电影", R.drawable.ic_category_1)); results.add(new Item(i*8 2,"酒店", R.drawable.ic_category_2)); results.add(new Item(i*8 3,"KTV", R.drawable.ic_category_3)); results.add(new Item(i*8 4,"外卖", R.drawable.ic_category_4)); results.add(new Item(i*8 5,"彩票", R.drawable.ic_category_5)); results.add(new Item(i*8 6,"电影", R.drawable.ic_category_6)); results.add(new Item(i*8 7,"游戏", R.drawable.ic_category_7)); } } results.remove(results.size()-1); results.add(new Item(results.size(), "更多", R.drawable.takeout_ic_more)); }
onViewCreated处理recyclerView
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); RecyclerAdapter adapter = new RecyclerAdapter(R.layout.item_grid,results); recyclerView = (RecyclerView)view; recyclerView.setHasFixedSize(true); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4)); recyclerView.addItemDecoration(new DividerGridItemDecoration(getActivity())); itemTouchHelper = new ItemTouchHelper(new MyItemTouchCallback(adapter).setOnDragListener(this)); itemTouchHelper.attachToRecyclerView(recyclerView); recyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerView) { @Override public void onLongClick(RecyclerView.ViewHolder vh) { if (vh.getLayoutPosition()!=results.size()-1) { itemTouchHelper.startDrag(vh); VibratorUtil.Vibrate(getActivity(), 70); //震动70ms } } @Override public void onItemClick(RecyclerView.ViewHolder vh) { Item item = results.get(vh.getLayoutPosition()); Toast.makeText(getActivity(),item.getId() " " item.getName(),Toast.LENGTH_SHORT).show(); } }); }
recyclerview实现ListView和GridView拖拽源代码下载链接: recyclerview拖拽排序 密码: 3kxx