Saya menggunakan pengikatan data dua arah dengan RecyclerView
saya untuk pertama kalinya dan saya bingung bagaimana cara mengirim daftar nilai ke adaptor RecyclerView
dari ViewModel
saya
Biasanya saya pergi ke Activity/Fragment
saya dan melakukan panggilan seperti ini untuk menyegarkan daftar RecyclerView
:
viewModel.getList().observe(viewLifecycleOwner, Observer { list ->
recyclerView.adapter = adapter(list)
})
Namun karena semuanya sedang dilakukan di ViewModel
sekarang dan melewatkan Activity/Fragment
, apa cara terbaik untuk mengirimkan daftarnya?
Model Tampilan:
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 Tata Letak:
<?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>