Android spinner Data Binding using XML and show the selected values

1 Line Solution

android:selectedItemPosition="@={item.selectedItemPosition}"

That’s it! No need to make custom BindingAdapter.

Spinner already supports two-way binding by attributes selection and
selectedItemPosition. See Android Documentation

You just need to use two way binding selectedItemPosition so that
change on spinner reflect on your model field.

Example

Item.class

public class Item extends BaseObservable {
    private int selectedItemPosition;

    @Bindable
    public int getSelectedItemPosition() {
        return selectedItemPosition;
    }

    public void setSelectedItemPosition(int selectedItemPosition) {
        this.selectedItemPosition = selectedItemPosition;
        notifyPropertyChanged(BR.selectedItemPosition);
    }
}

activity_main.xml

<variable
    name="item"
    type="com.sample.data.Item"/>

<android.support.v7.widget.AppCompatSpinner
    ...
    android:entries="@array/items"
    android:selectedItemPosition="@={item.selectedItemPosition}"
    >

MainActivity.java

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        binding.setItem(new Item());
        binding.getItem().setSelectedItemPosition(4); // this will change spinner selection.
        System.out.println(getResources().getStringArray(R.array.items)[binding.getItem().getSelectedItemPosition()]);
    }
}

If you need to get selected item from your code any time, then use this

binding.getItem().getSelectedItemPosition(); // get selected position
getResources().getStringArray(R.array.items)[binding.getItem().getSelectedItemPosition()]) // get selected item

Make your variable @Bindable if you need to programmatically change it.

binding.getItem().setSelectedItemPosition(4);

Otherwise you can remove @Bindable and notifyPropertyChanged(BR.selectedItemPosition);.

You can use any of BaseObservable or
ObservableField
or Live Data. It is up to you. I use BaseObservable because it is very simple., just extend from BaseObservable and all fields are observable now.

Leave a Comment