ฉันใช้การเชื่อมโยงข้อมูลแบบสองทางกับ RecyclerView
ของฉันเป็นครั้งแรก และฉันสับสนเกี่ยวกับวิธีการส่งรายการค่าไปยังอะแดปเตอร์ RecyclerView
จาก ViewModel
ของฉัน
โดยปกติฉันจะไปที่ Activity/Fragment
ของฉันและโทรแบบนี้เพื่อรีเฟรชรายการ RecyclerView
:
viewModel.getList().observe(viewLifecycleOwner, Observer { list ->
recyclerView.adapter = adapter(list)
})
แต่เนื่องจากตอนนี้ทุกอย่างเสร็จสิ้นแล้วใน ViewModel
และข้ามไปเหนือ Activity/Fragment
วิธีใดคือวิธีที่ดีที่สุดในการส่งรายการไป
ดูรุ่น:
class ViewModel : ViewModel() {
// This variable is binded to the layout so it has the value of the EditText
val editTextContent = MutableLiveData<String>()
// This function is also binded to the layout view
fun buttonClick() {
//Here it returns a list that I would send to the adapter
getList(editTextContent.value.toString())
// How else can I do this?
}
fun getList(search: String): MutableLiveData<List<Object>> = Repository.getList(search)
}
XML เค้าโครง:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewmodel"
type="com.example.app.ui.search.FragmentViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.search.Fragment">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={viewmodel.editTextContent}"
android:hint="Name" />
<Button
android:id="@+id/search_fragment_search_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"
android:onClick="@{() -> viewmodel.buttonClick()}"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/fragment_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</layout>