Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a popup options menu in a contextual action bar

I have an app with a NoActionBar theme. In my main activity I have an options menu that I created manually on the top of the screen (or by utilizing the built in device's options button).

In this main activity, I have a fragment with a listView where I apply the action mode long click functionality, to show the contextual action bar (CAB) for further user options.

Now, I try adding an options item to my CAB so it will contain some options like selecting all items in the listView, but since it's an item of the CAB, I can't really show the popup menu like in a regular activity. Further more, I want all the options menu callbacks (such as onOptionsItemSelected) to stay in the context of the CAB, in order to be able to continue to perform actions on the CAB.

Here's the code of my CAB:

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

    <item
        android:id="@+id/action_delete"
        android:orderInCategory="100"
        app:showAsAction="always"
        android:icon="@drawable/ic_action_delete"
        android:title="Delete"/>

    <item
        android:id="@+id/action_overflow"
        app:showAsAction="always"
        android:orderInCategory="200"
        android:icon="@drawable/ic_action_overflow"
        android:title="Options"
        android:visible="false"/>

</menu>
like image 424
limlim Avatar asked Nov 01 '22 12:11

limlim


1 Answers

Apparently I missed the built in feature of the CAB - a built in overflow menu that collapses some of the actions' items once the screen is too small to show them all.

Another manipulation that needs to be done in order to always collapse certain actions under that overflow menu is to set for each one of them:

android:showAsAction="never"
app:showAsAction="never"

So, say we have 3 actions (delete, selece_all, add) in the CAB, and we want two of them (select_all, add) to be collapsed always under the built in overflow menu, we'll set this in the CAB's xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mm="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_delete"
    android:orderInCategory="100"
    mm:showAsAction="always"
    android:icon="@drawable/ic_action_delete"
    android:title="Delete"/>

<item
    android:id="@+id/action_select"
    android:orderInCategory="200"
    android:showAsAction="never"
    mm:showAsAction="never"
    android:title="@string/select_all"/>

<item
    android:id="@+id/action_add"
    android:orderInCategory="300"
    android:showAsAction="never"
    mm:showAsAction="never"
    android:title="@string/button_add"/>

like image 140
limlim Avatar answered Nov 12 '22 12:11

limlim