malcoauri
malcoauri

Reputation: 12189

How to add dropdown menu to ActionBar in Android project?

I had been developing Android applications, but I don't know much about 4+ versions of Android well. Therefore, please help me - I have made Android application with tabs for navigation:

final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

But I also need to add dropdown menu to ActionBar for other goals. Can I do it? Please, if it's possible, give me an example. Thank you in advance.

Upvotes: 2

Views: 13422

Answers (2)

best wishes
best wishes

Reputation: 6624

Absolutely the best and and the simplest answer I found so far is here.

Basically, no need for custom layout in this case. Just set the actonViewClass:

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

And then handle it in onCreateOptionsMenu, 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

This is by far the simplest and cleanest solution. Credits to François POYER, the original author.

Upvotes: 3

Anup Cowkur
Anup Cowkur

Reputation: 20553

You can use something called an android spinner. It looks like this:

enter image description here

You can customize it in many ways to suit your apps design too.

Here's a great tutorial by Google on how to use these:

http://developer.android.com/guide/topics/ui/controls/spinner.html

If you want to add this to an action bar, you can do it via a spinner adapter as detailed here: http://developer.android.com/guide/topics/ui/actionbar.html#Dropdown

If you want to add icons to do certain actions, then you can see this: http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems

If you want to do certain actions in the bar itself (like search in the google search app) then see this: http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

If you want to add navigation tabs, then see this: http://developer.android.com/guide/topics/ui/actionbar.html#Tabs

Upvotes: 15

Related Questions