본문 바로가기
개인공부/android

[Kotlin] Adpater에서 Room Database Delete Event 받기

by 왕큰새 2022. 2. 3.
728x90

1. Adpater 매개변수로 onDeleteCallBack 이라는 변수 -> 람다 함수를 반환 

-> 람다함수는 Routine 값을 매개변수로, Unit을 리턴값으로 갖는다.

class RoutineAdapter(private val onDeleteCallBack: (Routine) -> Unit) : {}

 

2. Adpater item 중 클릭 되었을 때 onDeleteCallBack을 호출하고 싶은 곳에 작성

  override fun onBindViewHolder(holder: RoutineViewHolder, position: Int) {
        val currentItem = routineList[position]
        holder.binding.deleteBtn.setOnClickListener {
                        onDeleteCallBack(currentItem)           
        }
    }

 

 

3. Adpater를 생성하는 Fragment Or Activity에 Delete 함수 작성

private fun deleteRoutine(routine: Routine) {
    routineViewModel.deleteRoutine(routine)
    routineAdapter.notifyDataSetChanged()
}

 

4. Adpater의 매개변수로 함수 자체를 인자로 전달

 routineAdapter = RoutineAdapter(::deleteRoutine)

 

출처 

https://stackoverflow.com/questions/67878367/how-to-call-viewmodel-delete-from-recyclerview-adapter

 

How to call ViewModel.delete from RecyclerView Adapter?

I want to call my ViewModel.delete (Room Database) method from my Recyclerview Adapter but it's not working. Any ideas? I want to call the ViewModel in OnBindViewHolder like: holder.binding.

stackoverflow.com