I am trying to add this function to my RecyclerView
, that when I swipe one item either to the left or the right it gets deleted.
But when I execute my App I can't even swipe one of the items.
Appreciate any help
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(mRecyclerView);
ItemTouchHelper.SimpleCallback itemTouchHelperCallback= new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
mExampleList.remove(viewHolder.getAdapterPosition());
mAdapter.notifyDataSetChanged();
saveData();
}
By the way this RecyclerView
is not located in my MainActivity but in a Fragment that can be opened from the Drawer menu in the MainActivity, so maybe the problem lies there?
Okay so I have finally found the problem.
I just had to initialize the ItemTouchHelper in the method where the RecyclerView
is built instead of in the onCreate method.
So this is what the code looks like:
private void buildRecyclerView() {
mRecyclerView = view.findViewById(R.id.recyclerview);
mLayoutManager = new LinearLayoutManager(getActivity());
mAdapter = new ExampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
new ItemTouchHelper(itemTochHelperCallback).attachToRecyclerView(mRecyclerView);
mRecyclerView.setAdapter(mAdapter);
}
ItemTouchHelper.SimpleCallback itemTochHelperCallback=new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
mExampleList.remove(viewHolder.getAdapterPosition());
mAdapter.notifyDataSetChanged();
}
};