Pages

Thursday, June 04, 2015

Adding a dropdown (spinner) to toolbar in Android app

Here is a very elegant and simple solution on how to add a Spinner (a dropdown) to a toolbar in an Android app.
Add a Spinner as menu item and set the action view class

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >

  <item android:id="@+id/spinner"
    yourapp:showAsAction="ifRoom"
    yourapp:actionViewClass="android.widget.Spinner" />
</menu>

Then handle the contents in onCreateMenuItem, as usual.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_layout, menu);
    MenuItem item = menu.findItem(R.id.spinner);
    Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
    spinner.setAdapter(adapter); // set the adapter to provide layout of rows and content
    s.setOnItemSelectedListener(onItemSelectedListener); // set the listener, to perform actions based on item selection
} 

Source

No comments: