是否可以从ArrayAdapter
代替Spinner
为LiveData<List<T>>
构建List<T>
的{{1}}?
将ViewModel的LiveData返回值绑定到Spinner
的最佳实践是什么?
答案 0 :(得分:2)
如果这正是您的意思,那么:
class MyVM : ViewModel() {
...
private val mSpinnerData = MutableLiveData<List<String>>()
...
fun fetchSpinnerItems(): LiveData<List<String>> {
//fetch data
mSpinnerData.value = <some fetched list of Strings>
return mSpinnerData
}
}
在您的活动/片段之后:
class MyActivity : AppCompatActivity() {
private lateinit var mViewModel: MyVM
...
override fun onCreate(outState: Bundle?) {
//initialize your view model here...
mViewModel.fetchSpinnerItems().observe(this, Observer { spinnerData ->
val spinnerAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, spinnerData)
mSpinner.adapter = spinnerAdapter
})
...
}