Search code examples
androidandroid-layoutandroid-actionbar

Action Item acts as drop down menu


Is it possible to add Action Item in ActionBar, which show drop down menu on click?

paint example:

enter image description here

P.S. ActionBar already contains navigation drawer toggle button, title and overflow menu.

  1. Where do I initialize that button, in which xml?

  2. How do I set such drop down operations to Action Item?

  3. How to set the content of such drop down menu?

  4. And how to get access to specific item click action?

Some working code examples would be great!

Thanks in advance. Appreciate any help.


Solution

  • So I found solution by myself.

    You need to inflatean Action Item in onCreateOptionsMenu(Menu menu):

    getMenuInflater().inflate(R.menu.global_filters, menu);
    

    global_filters.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     tools:context=".NavigationActivity">
    
    <item android:id="@+id/action_filters"
        android:title="Фильтры"
        android:icon="@drawable/ic_filter_white"
        android:orderInCategory="100"
        app:showAsAction="ifRoom" />
    </menu>
    

    ...which is that downside arrow: enter image description here

    Then create a PopupMenu. I did it in onOptionsItemSelected:

     View menuItemView = findViewById(R.id.action_filters); // SAME ID AS MENU ID
        PopupMenu popupMenu = new PopupMenu(this, menuItemView);
        popupMenu.inflate(R.menu.popup_filters_user);
        popupMenu.show();
    

    and here you set .xml file with items of drop down menu in file popup_filters_user.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/filter_bought_user"
        android:title="Купленые"/>
    <item
        android:id="@+id/filter_price_user"
        android:title="Цена"/>
    <item
        android:id="@+id/filter_author_user"
        android:title="Автор"/>
    </menu>
    

    and hooray! Here's the result:

    enter image description here