Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DataBindingUtil with an Android spinner?

Tags:

java

android

I am trying to use the new Android data binding library and get the following error trying to populate a spinner with the selected value.

Error Message (during compilation in Android Studio):

Error:Execution failed for task ':app:compileDebugJavaWithJavac'. java.lang.RuntimeException: Found data binding errors. ****/ data binding error ****msg:Cannot find the setter for attribute 'app:selection' with parameter type java.lang.String. file:/Users/ove/Code/AndroidStudio/Samples/Receipts/app/src/main/res/layout/dialogfragment_inputamount_db.xml loc:40:29 - 40:44 ****\ data binding error ****

My layout file looks the following (not complete):

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

    <data>

        <variable
            name="receipt"
            type="com.example.model.Receipt" />
    </data>
    </LinearLayout>
    <Spinner
        android:layout_width="wrap_content"
        android:id="@+id/currency"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"
        android:entries="@array/currency_array"
        app:selection="@{receipt.currency}" />
    </LinearLayout>
</layout>

Anyone out there that has managed to get data binding to work with spinners?

Ove

like image 314
Ove Stoerholt Avatar asked Oct 07 '15 15:10

Ove Stoerholt


2 Answers

create a class BindingUtils and paste setSelection method

public class BindingUtils
  {
       @BindingAdapter({"bind:selection"})
       public static void setSelection(Spinner spinner, int position)
       {
            spinner.setSelection(position);
       }
  }

inside spinner

app:selection="@{receipt.currencyIdx}"

Thats all you have to do.

like image 102
Dheeraj Kumar Avatar answered Oct 30 '22 19:10

Dheeraj Kumar


The setter Spinner:setSelection inherited from AbsSpinner has int parameter - not String:

public void setSelection(int position)

you should pass a position, not the value of the selection

<Spinner
    android:layout_width="wrap_content"
    android:id="@+id/currency"
    android:layout_height="wrap_content"
    android:spinnerMode="dropdown"
    android:entries="@array/currency_array"
    app:selection="@{receipt.currencyIdx}" />
</LinearLayout>
like image 31
zacheusz Avatar answered Oct 30 '22 17:10

zacheusz