Android display a drop-down list on action bar

In default, the action bar displays only the icon and title of your application. However, Android allows you to customize the action bar to display other things such as drop-down list (Spinner), Button, EditText, ImageView, and so on. In this Android tip, I am going to show you how to display a Spinner widget on the action bar.

To achieve the goal, first you need a custom menu file (to be saved in the res/menu folder) that has a Spinner. The android:actionViewClass="android.widget.Spinner" tells Android system that the item of the menu is a Spinner. If you want a Buttom item instead, simply change the Spinner to Button.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="">

  <item android:id="@+id/item1"

Next, in the onCreateOptionsMenu() method of the MainActivity, you comment out the line: getMenuInflater().inflate(, menu); to disable the default menu. Then inflate the custom menu using the inflate() method of the MenuInflater class. After that you can use the findItem() method of the Menu class to create a reference to the Spinner menu item. You will add the setupSpinner() method to the MainActivity class to assign items to the Spinners.

package com.example.androidexample;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {


public boolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(, menu);
//Use custom menu instead
MenuInflater inflater = getMenuInflater();
//Inflate the custom menu
inflater.inflate(, menu);
//reference to the item of the menu
MenuItem mitem=menu.findItem(;
Spinner spin =(Spinner) mitem.getActionView();
return true;

public void setupSpinner(Spinner spin){
String[] items={"Home","Search","Settings"};
//wrap the items in the Adapter
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.spinner_item,items);
//assign adapter to the Spinner



Posted by: Dara | post date: 09-25-2014 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.