peterc
peterc

Reputation: 7873

How to bind to an Android Spinner using a ViewModel

I am trying to find out how to bind both the list items, and the selected value/index of an Android Spinner (I am pretty new to Android / Kotlin)

I have the following

    <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"/>

and in the View Model

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

By trial and error I could set just strings to the Spinner items (the MidiDeviceInfo would have been better, but string will do)

However, I cannot get a binding to get the selectedItem to work.

I have tried many things, but with the above, I have the error

    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}]}

Anyone know a way to do this?

Upvotes: 2

Views: 1895

Answers (1)

Sam Chen
Sam Chen

Reputation: 8867

Try using android:selectedItemPosition="@={viewModel.devicePosition}" instead of app:selectedValue="@={viewModel.devicePosition}".

Upvotes: 4

Related Questions