我有一个带有Spinner小部件的布局,其中包含带有活动类型的Spinner:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="android.view.View"/>
<variable
name="viewModel"
type=".MainViewModel"/>
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/app_bar_main"
tools:context=".qwe.MaincActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@{viewModel.activityTypes}"
android:id="@+id/activity_types"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
</layout>
和viewModel:
class MainViewModel
@Inject
constructor(
private var activityTypeRepository: ActivityTypeRepository,
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
val activityTypes = MutableLiveData<List<ActivityType>>()
fun loadActivityTypes() {
compositeDisposable.addAll(activityTypeRepository.getAll()
?.subscribeOn(Schedulers.newThread())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribeWith(
object : DisposableObserver<List<ActivityType>>() {
override fun onComplete() {
}
override fun onNext(t: List<ActivityType>) {
activityTypes.value = t
}
override fun onError(e: Throwable) {
}
}
))
}
override fun onCleared() {
super.onCleared()
if (!compositeDisposable.isDisposed) {
compositeDisposable.dispose()
}
}
}
如何绑定viewModel中的Spinner和activityTypes 我想将所有数据从activityTypes加载到微调器 并在微调器中选择某些项目时将一些信息存储到viewModel中
活动类型是复杂的对象,其中包含一些字段,我需要显示其中一个字段,然后从列表中选择整个对象activityTypes 请说明如何做到这一点
class ActivityType(
var id: String,
var name: String,
//other fields...
) : BaseObservable()