Как обновить Fragment или RecycleView из адаптера?

Я пишу свой первый проект на kotlin - приложение на андроид с расписанием. в моем Fragment лежит recycleView, в recycleView лежат занятия в виде cardview, у recycleView есть адаптер. так получилось, что в адаптере у меня логика удаления выбранной карточки с занятием. Как я могу обновить фрагмент или recycleview прямиком из адаптера, чтобы после удаления сразу отображалось корректное расписание? github проекта: https://github.com/ersnick/Schedule

LessonsAdapter.kt:

class LessonsAdapter(public var lessons: List<Lesson>, var context: Context):
RecyclerView.Adapter<LessonsAdapter.MyViewHolder>() {
//lateinit var binding: RemoveOrEditDialogBinding
class MyViewHolder(view: View): RecyclerView.ViewHolder(view){
    val lessonDay: TextView = view.findViewById(R.id.lesson_list_day)
    val lessonTime: TextView = view.findViewById(R.id.lesson_list_time)
    val lessonName: TextView = view.findViewById(R.id.lesson_list_name)
    val lessonTeacherName: TextView = view.findViewById(R.id.lesson_list_teacher_name)
    val lessonClassroom: TextView = view.findViewById(R.id.lesson_list_classroom)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.lesson_in_list, parent, false)
    return MyViewHolder(view)
}

override fun getItemCount(): Int {
    return lessons.count()
}

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    holder.lessonClassroom.text = lessons[position].classroom
    holder.lessonTeacherName.text = lessons[position].teacherName
    holder.lessonDay.text = lessons[position].day
    holder.lessonName.text = lessons[position].lessonName + " (" + lessons[position].lessonType + ")"
    holder.lessonTime.text = lessons[position].timeStart + " - " + lessons[position].timeEnd

    holder.itemView.setOnClickListener {
        val dialog = Dialog(context)
        dialog.setContentView(R.layout.remove_or_edit_dialog)
        dialog.show()
        val textDelete: TextView = dialog.findViewById(R.id.delete_lesson)
        val textEdit: TextView = dialog.findViewById(R.id.edit_lesson)

        textDelete.setOnClickListener {
            val db = DbHelper(context, null)
            db.writableDatabase
            db.delLesson(lessons[position])
            dialog.dismiss()

            //Пытаюсь обновить фрагмент
            //supportFragmentManager
            //    .beginTransaction()
            //    .replace(R.id.schedule, FirstWeekFragment.newInstance())
            //    .commit()
        }

        textEdit.setOnClickListener {
            //TODO open edit activity
        }
    }
}

}

MainActivity.kt где лежит фрагмент:

class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    val bChangeWeek: Button = binding.changeWeekButton
    val addLessonButton: FloatingActionButton = findViewById(R.id.addLessonButton)

    addLessonButton.setOnClickListener {
        val intent = Intent(this, addLessonActivity::class.java)
        startActivity(intent)
    }

    binding.changeWeekButton.setOnClickListener {
        if (bChangeWeek.text == "Первая неделя") {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.schedule, SecondWeekFragment.newInstance())
                .commit()
            bChangeWeek.text = "Вторая неделя"
        }
        else {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.schedule, FirstWeekFragment.newInstance())
                .commit()
            bChangeWeek.text = "Первая неделя"
        }
    }

    supportFragmentManager
        .beginTransaction()
        .replace(R.id.schedule, FirstWeekFragment.newInstance())
        .commit()
}

}

FirstWeekFragment.kt:

class FirstWeekFragment : Fragment() {
lateinit var binding: FragmentFirstWeekBinding
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    binding = FragmentFirstWeekBinding.inflate(inflater)
    return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val lessonList: RecyclerView = binding.lessonWeek1List
    var lessons = arrayListOf<Lesson>()
    val db = DbHelper(requireContext(), null)
    var dbLessons = db.getLessonFirstWeek()
    lessons.addAll(dbLessons)
    for (lesson in dbLessons){
        //TODO sort per day and time
    }

    //hardcode
    //lessons.add(Lesson("Фронтенд", "18:20", "21:25", "132", "Практика", "Пятница", "Первая", "Не помню"))
    //lessons.add(Lesson("Технологии прикладного программирования", "9:40", "16:30", "132", "Практика", "Суббота", "Первая", "Веригин Н.В."))
    //lessons.add(Lesson("Базы данных", "16:45", "17:15", "132б", "Лекция", "Суббота", "Первая", "Барабанщиков"))

    lessonList.layoutManager = LinearLayoutManager(lessonList.context)
    lessonList.adapter = LessonsAdapter(lessons, lessonList.context)
}

companion object {

    @JvmStatic fun newInstance() = FirstWeekFragment()
}

}


Ответы (0 шт):