@@ -7,11 +7,16 @@ import android.widget.Toast
77import androidx.fragment.app.Fragment
88import androidx.fragment.app.viewModels
99import androidx.lifecycle.Observer
10+ import androidx.recyclerview.widget.ItemTouchHelper
1011import androidx.recyclerview.widget.LinearLayoutManager
12+ import androidx.recyclerview.widget.RecyclerView
1113import com.decimalab.todokotlin.R
14+ import com.decimalab.todokotlin.data.models.ToDoData
1215import com.decimalab.todokotlin.data.viewmodel.ToDoViewModel
1316import com.decimalab.todokotlin.databinding.FragmentListBinding
1417import com.decimalab.todokotlin.fragments.BaseViewModel
18+ import com.decimalab.todokotlin.fragments.list.adapter.ListAdapter
19+ import com.google.android.material.snackbar.Snackbar
1520
1621class ListFragment : Fragment () {
1722
@@ -53,6 +58,41 @@ class ListFragment : Fragment() {
5358 val recyclerView = binding.recyclerView
5459 recyclerView.adapter = adapter
5560 recyclerView.layoutManager = LinearLayoutManager (requireActivity())
61+
62+ swipeToDelete(recyclerView)
63+ }
64+
65+ private fun swipeToDelete (recyclerView : RecyclerView ) {
66+ val swipeToDeleteCallback = object : SwipeToDelete () {
67+ override fun onSwiped (viewHolder : RecyclerView .ViewHolder , direction : Int ) {
68+ val deletedItem = adapter.dataList[viewHolder.adapterPosition]
69+ // Delete Item
70+ mToDoViewModel.deleteItem(deletedItem)
71+
72+ Toast .makeText(
73+ requireContext(),
74+ " Deleted" ,
75+ Toast .LENGTH_SHORT
76+ ).show()
77+
78+ adapter.notifyItemRemoved(viewHolder.adapterPosition)
79+ // Restore Deleted Item
80+ restoreDeletedData(viewHolder.itemView, deletedItem)
81+ }
82+ }
83+ val itemTouchHelper = ItemTouchHelper (swipeToDeleteCallback)
84+ itemTouchHelper.attachToRecyclerView(recyclerView)
85+ }
86+
87+ private fun restoreDeletedData (view : View , deletedItem : ToDoData ) {
88+ val snackBar = Snackbar .make(
89+ view, " Deleted '${deletedItem.title} '" ,
90+ Snackbar .LENGTH_LONG
91+ )
92+ snackBar.setAction(" Undo" ) {
93+ mToDoViewModel.insertData(deletedItem)
94+ }
95+ snackBar.show()
5696 }
5797
5898 override fun onCreateOptionsMenu (menu : Menu , inflater : MenuInflater ) {
0 commit comments