LiveData的微调适配器

时间:2019-01-09 13:19:24

标签: java android

是否可以从ArrayAdapter代替SpinnerLiveData<List<T>>构建List<T>的{​​{1}}?

将ViewModel的LiveData返回值绑定到Spinner的最佳实践是什么?

1 个答案:

答案 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
    })
  ...
}