How to invoke the ActionBar's ContextMenu-like behavior?
Asked Answered
C

3

17

In Android 3.0, when you select some text for example, the ActionBar switches to a ContextMenu-like mode, which enables you to do actions with the selected text: copy/share/etc, and a "Done" button appears on the left side to enable the user to leave this mode.

How can I switch the ActionBar into this mode in my app (with my menu items of course)? I just couldn't find this in the docs.

Curtice answered 28/5, 2011 at 15:32 Comment(0)
F
18

Yeah, I couldn't find it either -- I had to ask at Google I|O.

Use startActionMode(). Here is one of their samples that demonstrates it. I need to do more work in this area myself.

Facer answered 28/5, 2011 at 15:48 Comment(4)
Whoa, now that's a function well hidden. Thanks!Aldercy
is it just me or does calling this not work properly with MultiChoiceModeListener? It seems when I use this in my Activity the 'onItemCheckedStateChanged' callback is never executed. The rest of the ActionMode.Callback methods get called as expected.Overlying
Use [startSupportActionMode (ActionMode.Callback callback)](developer.android.com/reference/android/support/v7/app/… for appcompat projects instead.Manfred
@Facer I have a similar problem invoking the CAB using startSupportActionMode for a RecyclerView list. I would appreciate any help or insights you could provide, here: #47406998Causerie
T
33

enter image description here

To use the new contextual action bar, see "Enabling the contextual action mode for individual views". It states:

If you want to invoke the contextual action mode only when the user selects specific views, you should:

  1. Implement the ActionMode.Callback interface. In its callback methods, you can specify the actions for the contextual action bar, respond to click events on action items, and handle other lifecycle events for the action mode.
  2. Call startActionMode() when you want to show the bar (such as when the user long-clicks the view).

For example:

  1. Implement the ActionMode.Callback interface:
    
    private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
    
        // Called when the action mode is created; startActionMode() was called
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate a menu resource providing context menu items
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);
            return true;
        }
    
        // Called each time the action mode is shown. Always called after onCreateActionMode, but
        // may be called multiple times if the mode is invalidated.
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false; // Return false if nothing is done
        }
    
        // Called when the user selects a contextual menu item
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.menu_share:
                    shareCurrentItem();
                    mode.finish(); // Action picked, so close the CAB
                    return true;
                default:
                    return false;
            }
        }
    
        // Called when the user exits the action mode
        @Override
        public void onDestroyActionMode(ActionMode mode) {
            mActionMode = null;
        }
    };
    
    

    Notice that these event callbacks are almost exactly the same as the callbacks for the options menu, except each of these also pass the ActionMode object associated with the event. You can use ActionMode APIs to make various changes to the CAB, such as revise the title and subtitle with setTitle() and setSubtitle() (useful to indicate how many items are selected).

    Also notice that the above sample sets the mActionMode variable null when the action mode is destroyed. In the next step, you'll see how it's initialized and how saving the member variable in your activity or fragment can be useful.

  2. Call startActionMode() to enable the contextual action mode when appropriate, such as in response to a long-click on a View:
    
    someView.setOnLongClickListener(new View.OnLongClickListener() {
        // Called when the user long-clicks on someView
        public boolean onLongClick(View view) {
            if (mActionMode != null) {
                return false;
            }
    
            // Start the CAB using the ActionMode.Callback defined above
            mActionMode = getActivity().startActionMode(mActionModeCallback);
            view.setSelected(true);
            return true;
        }
    });
    
    

    When you call startActionMode(), the system returns the ActionMode created. By saving this in a member variable, you can make changes to the contextual action bar in response to other events. In the above sample, the ActionMode is used to ensure that the ActionMode instance is not recreated if it's already active, by checking whether the member is null before starting the action mode.

Enabling batch contextual actions in a ListView or GridView

If you have a collection of items in a ListView or GridView (or another extension of AbsListView) and want to allow users to perform batch actions, you should:

For example:

ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

    @Override
    public void onItemCheckedStateChanged(ActionMode mode, int position,
                                          long id, boolean checked) {
        // Here you can do something when items are selected/de-selected,
        // such as update the title in the CAB
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        // Respond to clicks on the actions in the CAB
        switch (item.getItemId()) {
            case R.id.menu_delete:
                deleteSelectedItems();
                mode.finish(); // Action picked, so close the CAB
                return true;
            default:
                return false;
        }
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        // Inflate the menu for the CAB
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.context, menu);
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        // Here you can make any necessary updates to the activity when
        // the CAB is removed. By default, selected items are deselected/unchecked.
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        // Here you can perform updates to the CAB due to
        // an invalidate() request
        return false;
    }
});

That's it. Now when the user selects an item with a long-click, the system calls the onCreateActionMode() method and displays the contextual action bar with the specified actions. While the contextual action bar is visible, users can select additional items.

In some cases in which the contextual actions provide common action items, you might want to add a checkbox or a similar UI element that allows users to select items, because they might not discover the long-click behavior. When a user selects the checkbox, you can invoke the contextual action mode by setting the respective list item to the checked state with setItemChecked().

Torosian answered 30/9, 2012 at 21:58 Comment(1)
Is it considered acceptable to just copy content from official documentation into an answer? The original content is creative-commons licenced, but the attribution is not clear enough here.Schluter
F
18

Yeah, I couldn't find it either -- I had to ask at Google I|O.

Use startActionMode(). Here is one of their samples that demonstrates it. I need to do more work in this area myself.

Facer answered 28/5, 2011 at 15:48 Comment(4)
Whoa, now that's a function well hidden. Thanks!Aldercy
is it just me or does calling this not work properly with MultiChoiceModeListener? It seems when I use this in my Activity the 'onItemCheckedStateChanged' callback is never executed. The rest of the ActionMode.Callback methods get called as expected.Overlying
Use [startSupportActionMode (ActionMode.Callback callback)](developer.android.com/reference/android/support/v7/app/… for appcompat projects instead.Manfred
@Facer I have a similar problem invoking the CAB using startSupportActionMode for a RecyclerView list. I would appreciate any help or insights you could provide, here: #47406998Causerie
K
6

Maybe a bit late but here's a tutorial for the actionmode: http://www.vogella.com/articles/AndroidListView/article.html#listview_actionbar

Koehn answered 16/8, 2012 at 9:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.