简体   繁体   中英

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)

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);

My solution: XML:

  <androidx.appcompat.widget.AppCompatSpinner
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:background="@drawable/button_background"
                android:entries="@{viewModel.items}"
                android:padding="5dp"
                android:selectedItemPosition="@{viewModel.itemPosition}" />

ViewModel:

  var items: ArrayList<Item> = ArrayList()
  var itemPosition = MutableLiveData<Int>()

Activity/Fragment:

   viewModel.itemPosition.observe(requireActivity(),
        object : Observer<Int> {
            override fun onChanged(t: Int?) {
                //you will get the position on selection os spinner
                //get value by position

        })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM