如何使用数据绑定初始化微调器

时间:2019-07-03 14:26:02

标签: android kotlin data-binding android-spinner

我正在使用数据绑定来绑定我的微调器 一切正常,除了第一次从服务器加载数据时,我初始化了微调器,并从viewModel中设置了一个选定的值,但是它不起作用 如果我关闭并重新打开页面,则会在微调器中找到所选的值

这是我的微调XML:

<Spinner
         android:id="@+id/construction_site"
         android:layout_width="match_parent"
         android:layout_height="40dp"
         android:prompt="@string/select_existing_construction_site"
         app:entries="@{viewModel.constructionSiteAdapter}"
         app:selectedValue="@{viewModel.constructionSite}"
         style="@style/Widget.AppCompat.DropDownItem.Spinner">
</Spinner>

在viewModel中,我以这种方式初始化微调器:

class RightDrawerViewModel : ViewModel(){
     val constructionSiteAdapter: ArrayAdapter<ConstructionSite> by lazy {
        ConstructionSiteAdapter(
        App.context,
        R.layout.cell_construction_site_list_item,
        ArrayList()
       )
     }

     fun bind(constructionSite: ConstructionSite) {
         constructionSiteAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
         constructionSiteAdapter.clear()
         this.constructionSite.value = constructionSite // here I set the selected site to the spinner using data binding
         setConstructionSites(constructionSite)
         loadConstructionSites() // this method, load all sites from server and add them to the spinner
     }
}

这是我的绑定适配器:

@BindingAdapter(value = ["selectedValue", "selectedValueAttrChanged", "entries"], requireAll = false)
fun setEntries(view: Spinner, newSelectedValue: ConstructionSite?, bindingListener: InverseBindingListener?, adapter: ArrayAdapter<*>) {
    view.adapter = adapter
    view.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
         override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
            bindingListener?.onChange()
         }

         override fun onNothingSelected(parent: AdapterView<*>) {}
    }
    if (newSelectedValue != null) {
         val pos = (view.adapter as? ArrayAdapter<ConstructionSite>)?.getPosition(newSelectedValue)
         if (pos != null) view.setSelection(pos, true)
    }
}

@InverseBindingAdapter(attribute = "selectedValue", event = "selectedValueAttrChanged")
fun getSelectedValue(view: Spinner): ConstructionSite {
    return view.selectedItem as ConstructionSite
}

问题是this.constructionSite.value = constructionSite不起作用,并且在第一次加载时,微调框没有选定的值

0 个答案:

没有答案