【发布时间】:2021-04-18 23:12:28
【问题描述】:
我正在尝试观察 MutableLiveData 并刷新 RecycleView,但它不起作用。这是我的片段代码:
class NowyZestaw : Fragment() {
val setEditModeViewModel: SetEditModeViewModel by activityViewModels()
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
val bazaModel: BazaModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.nowy_zestaw, container, false)
root.findViewById<RecyclerView>(R.id.flashcard_recycler).isNestedScrollingEnabled = false
return root
}
@SuppressLint("ShowToast")
override fun onViewCreated(root: View, savedInstanceState: Bundle?) {
val addFlashcard: Button = root.findViewById(R.id.dodajFiszke)
addFlashcard.setOnClickListener {
val fiszka = Fiszka(0, "test", "test", 1)
// bazaModel.dodajFiszke(fiszka)
setEditModeViewModel.addNewFlashcard(Fiszka(1, "raz", "raz", 1))
}
val recyclerView: RecyclerView = root.findViewById(R.id.flashcard_recycler)
recyclerView.layoutManager = LinearLayoutManager(root.context)
val adapter = SetAdapter()
recyclerView.adapter = adapter
setEditModeViewModel.flashcards.observe(viewLifecycleOwner, Observer { flashcardList ->
Log.d("ANDROID", flashcardList.size.toString())
adapter.submitList(flashcardList)
})
}
}
这是我的视图模型:
class SetEditModeViewModel : ViewModel() {
val flashcards = MutableLiveData<MutableList<Fiszka>>().apply {
value = mutableListOf()
}
fun addNewFlashcard(item: Fiszka) {
flashcards.value?.add(item)
flashcards.value = flashcards.value
}
}
和 xml 行:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/flashcard_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="@layout/nowa_fiszka" />
</RelativeLayout>
当我单击控制台中的按钮时,会显示正确的列表大小,因此这意味着已通知观察到。例如,当我更改智能手机方向时,项目会出现在回收视图中。更重要的是,如果我观察 Room 数据库,返回 LiveData 一切正常。也许它只适用于 LiveData
,不适用于 MutableLiveData
【问题讨论】:
标签: android android-recyclerview mutablelivedata