【问题标题】:Databinding to Spinner using Static array using mvvm pattern使用 mvvm 模式使用静态数组将数据绑定到 Spinner
【发布时间】:2020-01-29 07:29:56
【问题描述】:

我正在尝试通过获取静态数组将数据绑定应用到微调器。我对如何通过这种 MVVM 方法获取所选项目字符串感到困惑。请帮助我。您的帮助将不胜感激

这是我有微调器的 xml

 <Spinner
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:entries="@array/service_type"
                            android:id="@+id/company_profile_grade_spinner"
                            />

我真的不知道如何在我的视图模型中获取所选项目的值。

【问题讨论】:

  • String text = spinner.getSelectedItem().toString(); 将此文本发送到 viewmodel viewModel.spinnerSelectedText(text) 并通过实时数据获取它viewModel.getSpinnerSelecetedtext().observe(this, string -&gt;{})
  • 但是如何在单击微调器项目时收到通知
  • viewModel.spinnerSelectedText(text) 在 vi​​ewmodel 的这个方法中更新 livedata 并观察这个 live data
  • 你能帮我写代码吗?我第一次尝试更新它。第二次点击监听器未通知
  • 使用spinner.setOnItemSelectedListener内部监听器onItemSelected方法集再次设置为viewModel.spinnerSelectedText(text)

标签: android kotlin android-spinner android-databinding android-mvvm


【解决方案1】:

您可以在ViewModel 中使用MutableLiveData&lt;Int&gt;(),它会根据微调器选择为您提供选定的项目位置。然后您可以使用它从基于位置选择的列表中查找项目。请参见下面的示例:

class SomeViewModel: ViewModel() {
    val spinnerSelectedPosition = MutableLiveData<Int>() // This gets updated once spinner item selection changes

    /** 
     * Created new mediator LiveData that provides changes based on position change from spinnerSelectedPosition
     * Use this live data as selected item which you can find from list provided to spinner with selected position got from spinnerSelectedPosition
     */
    val selectedItemFromSpinner: LiveData<DesiredItemClass> = MediatorLiveData<DesiredItemClass>().apply {
        addSource(spinnerSelectedPosition) { pos: Int? ->
            value = listFromSpinner.get(pos)
        }
    }
}

并将此属性添加到布局xml中进行选择配置:

<Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/service_type"
    android:selectedItemPosition="@={ViewModel.spinnerSelectedPosition}" // Use this attr for spinner selection notification with two way binding
    android:id="@+id/company_profile_grade_spinner" />

【讨论】:

  • 谢谢 .. 我怎样才能为电台组做数据绑定?
  • 您应该提出不同的问题或编辑相同的问题,以便我了解您面临的问题。
  • 如果我想从服务器获取列表而不是静态列表,请自行确定。我怎么办?
  • 例如,如果您从服务器获得列表,则您的 ViewModel 是中间的,它将持有来自服务器的该列表的 LiveData 的引用。在这种情况下,您已经可以通过 LiveData 在 ViewModel 中本地访问它。
  • 我不能像现在这样在 spinner 的条目中附加它吗?
猜你喜欢
  • 1970-01-01
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 2012-02-11
相关资源
最近更新 更多