Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android spinner data binding with xml layout

I'm using DataBinding class to bind data from the model to the UI elements. I could get the binding working for an EditText using android:text="@{data.testData}". This somehow doesn't work for a Spinner. Any ideas or solutions to get the data from the Pojo class and display it on a spinner (I have 45 spinners)

like image 359
Vivian Ambrose Avatar asked Jan 23 '16 10:01

Vivian Ambrose


1 Answers

Here is an example, that I used to do it:

First, your layout xml (example my_layout.xml):

<?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="spinnerAdapter"
            type="android.widget.ArrayAdapter" />
    </data>

...

    <android.support.v7.widget.AppCompatSpinner
                android:id="@+id/spinner"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:adapter="@{spinnerAdapter}" />

....
</layout>

Then your java code (MyLayoutBinding mBinding):

adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, mData);
mBinding.setSpinnerAdapter(adapter);
like image 81
maohieng Avatar answered Oct 24 '22 18:10

maohieng