【发布时间】:2021-12-25 03:43:48
【问题描述】:
song_item.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="song"
type=".models.Song" />
<variable
name="viewModel"
type=".SongDetailViewModel" />
</data>
<TextView
android:id="@+id/txt_song_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:selected="@{safeUnbox(viewModel.currentData.id == song.id)}"
/>
</layout>
SongAdapter.kt
我正在寻找一种将 song_item 中的 viewModel 绑定到我的适配器的方法。
-
我需要初始化 SongDetailViewModel。
-
在片段中我可以做到:
private val viewModel: SongDetailViewModel by viewModels()
但是我将如何在我的适配器中做到这一点:
class SongAdapter(
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
inner class ViewHolderSong(private val binding: ViewDataBinding) :
RecyclerView.ViewHolder(binding.root), View.OnClickListener {
private fun bindSong(song: Song) {
binding as SongItemBinding
binding.apply {
this.song = song
this.viewModel = songDetailViewModel <--- here, I don't know how to initialize this viewModel inside the adapter
executePendingBindings()
rootLyt.setOnClickListener(this@ViewHolderSong)
icMore.setOnClickListener(this@ViewHolderSong)
}
}
}
}
【问题讨论】:
-
为什么要在这里传递一个视图模型?视图模型的范围应该是片段/导航图/活动。您不会(也不需要)在适配器中获得 ViewModel 的任何好处。如果你真的需要,只需传递一个简单的 kotlin 类。否则,您可以只从适配器发出事件并在片段/活动或它们的视图模型中处理它们。
标签: java android xml kotlin adapter