Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

android - Drop Down Menu on Action bar

I am working on an android application Menu with Action Bar, I want to put the dropdown menu in the action bar like the one present in Google Maps application. Google Maps ActionBar

Can somebody help me? How to achieve this Please point to some easy tutorial that I can follow.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add this to your activity onCreate() method:

// Adapter
SpinnerAdapter adapter =
        ArrayAdapter.createFromResource(this, R.array.actions,
        android.R.layout.simple_spinner_dropdown_item);

// Callback
OnNavigationListener callback = new OnNavigationListener() {

    String[] items = getResources().getStringArray(R.array.actions); // List items from res

    @Override
    public boolean onNavigationItemSelected(int position, long id) {

        // Do stuff when navigation item is selected

        Log.d("NavigationItemSelected", items[position]); // Debug

        return true;

    }

};

// Action Bar
ActionBar actions = getActionBar();
actions.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actions.setDisplayShowTitleEnabled(false);
actions.setListNavigationCallbacks(adapter, callback);

This example requires an array resource for the list items:

res/values/arrays.xml

<string-array name="actions">
    <item>Item 1</item>
    <item>Item 2</item>
    <item>Item 3</item>
</string-array>

Alternatively you could create your own adapter and layout extended from SpinnerAdapter to display more advanced or dynamic list items.

To make the activity onCreate code even neater you could also change your Activity to implement OnNavigationListener and add the override onNavigationItemSelected with the callback code. Then change "callback" to "this" in the setListNavigationCallbacks() method.

Please note you will need to target API 11+ for the action bar, otherwise you will need to add version checking or a support library.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...