I have successfully implemented the swipe to delete action within my recyclerView.
The list I inflate the recyclerView with is locally stored and isn't in any database.
What I tried to do is to save the element to a temporary variable and if the user presses the undo button, I would restore it.
This is my code:
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition //get position which is swipe
if (direction == ItemTouchHelper.LEFT) { //if swipe left
val tmp = activeSubs[position] //temporary variable
activeSubs.removeAt(position)
adapter!!.removeItem(position)
val layout = find<View>(R.id.active_subs_recycler)
Snackbar.make(layout, "Subscription Deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", { _ ->
activeSubs.add(position-1, tmp)
adapter!!.notifyDataSetChanged()
})
}
}
My problem is that the SnackBar isn't shown at all, but the element is saved in the temporary variable and deleted from the list.
What am I doing wrong?
P.S. I've looked into other answers here on SO but they suggested to use a Dialog. I really need to use a Snackbar though
After setAction you forgot to call .show() so your code will be like this:
Snackbar.make(layout, "Subscription Deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", { _ ->
activeSubs.add(position-1, tmp)
adapter!!.notifyDataSetChanged()
})
.show()
For example, I have achieved your goal using this scenario. In Main Activity
tvTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tempValue = etUsername.getText().toString();
etUsername.setText("");
Snackbar.make(view, "Subscription Deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", new editTextListener())
.show();
}
});
Used inner class for listener:
private class editTextListener implements View.OnClickListener {
@Override
public void onClick(View view) {
etUsername.setText(tempValue);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With