【问题标题】:How to bind to an Android Spinner using a ViewModel如何使用 ViewModel 绑定到 Android Spinner
【发布时间】:2023-02-07 13:00:17
【问题描述】:

我正在尝试找出如何绑定列表项和 Android Spinner 的选定值/索引(我对 Android/Kotlin 很陌生)

我有以下

    <layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <import type="com.example.app.Modes" />
        <variable
            name="viewModel"
            type="com.example.app.MainActivityViewModel" />
    </data>

   ....

    <Spinner
        android:layout_row="17"
        android:layout_column="2"
        android:id="@+id/spinner1"
        android:layout_width="1200px"
        android:entries="@{viewModel.devicesDescriptions}"
        app:selectedValue="@={viewModel.devicePosition}"
        android:layout_height="wrap_content"
        android:background="@android:drawable/btn_dropdown"
        android:spinnerMode="dropdown"/>

在视图模型中

    val devicesDescriptions = ObservableArrayList<String>()
    var devices = listOf<MidiDeviceInfo>()
    fun setFoundDevices(d: MutableList<MidiDeviceInfo>) {
        devices = d
        for (dev in devices)
            devicesDescriptions.add(dev.toString())
    }

通过反复试验,我可以只将字符串设置为 Spinner 项目(MidiDeviceInfo 会更好,但字符串可以)

但是,我无法获得绑定以使 selectedItem 工作。

我已经尝试了很多东西,但是在上面,我有错误

    Found data binding error(s):
    [databinding] {"msg":"Cannot find a getter for \u003candroid.widget.Spinner app:selectedValue\u003e that accepts parameter type \u0027java.lang.String\u0027\n\nIf a binding adapter provides the getter, check that the adapter is annotated correctly and that the parameter type matches.","file":"app\\src\\main\\res\\layout\\activity_main.xml","pos":[{"line0":334,"col0":4,"line1":343,"col1":39}]}

有人知道这样做的方法吗?

【问题讨论】:

    标签: android kotlin data-binding android-spinner android-viewmodel


    【解决方案1】:

    尝试使用 android:selectedItemPosition="@={viewModel.devicePosition}" 而不是 app:selectedValue="@={viewModel.devicePosition}"。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 2014-08-06
    • 2011-11-30
    相关资源
    最近更新 更多