滑动以删除Android recyclerview不起作用

时间:2018-06-30 19:44:12

标签: java android swipe recyclerview-layout

@Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_tab2, container, false);

            dbManager = new DBManager(getContext(), null, null, 1);
            items = dbManager.getAllShoppingItems();
            recyclerView = view.findViewById(R.id.recyclerview);
            adapter = new Adapter(getActivity(), items);
            recyclerView.setAdapter(adapter);
            ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
            itemTouchHelper.attachToRecyclerView(recyclerView);
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            setUserVisibleHint(true);   //Ensure keyboard is hidden
            return view;
        }

        ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP |
                ItemTouchHelper.DOWN, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                Collections.swap(items,viewHolder.getAdapterPosition(), target.getAdapterPosition());
                adapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                adapter.notifyItemChanged(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                dbManager.deleteAllItems();
                for (int i = 0; i < items.size(); i++) {
                    dbManager.addItem(items.get(i));
                }
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                    items.remove(viewHolder.getAdapterPosition());
                    adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
                    //and notify database item deleted
                    dbManager.deleteItem(items.get(viewHolder.getAdapterPosition()).getItemName());
            }

            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder)
            {
                return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
                        ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.LEFT);
            }
        };

1 个答案:

答案 0 :(得分:1)

@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            int swipeFlags = ItemTouchHelper.LEFT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }