Is it possible to construct ArrayAdapter
for Spinner
from LiveData<List<T>>
instead of normally List<T>
?
What is the best practice to bind a ViewModel's LiveData returned value to a Spinner
?
If It is exactly what do you mean, so:
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
}
}
And after in your activity/fragment:
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
})
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.