ccd
ccd

Reputation: 6918

Spinner two-way binding using selectedItemPosition

After checking the official doc, if I want to data-binding spinner to my viewModel, I need to use selectedItemPosition in my xml file.

<Spinner
    android:id="@+id/categorySpinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:selectedItemPosition="@={viewModel.categoryIdItemPosition}"
/>

But I find there is no android:selectedItemPosition option below Spinner tag.

Upvotes: 0

Views: 1155

Answers (1)

Surbhi Aggarwal
Surbhi Aggarwal

Reputation: 907

Try android.support.v7.widget.AppCompatSpinner with selectedItemPosition

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

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

Upvotes: 2

Related Questions