How to close an ActionMode menu programmatically on Honeycomb?
Asked Answered
K

3

44

In my application there is a ListFragment where each item from the list contains a checkbox. Whenever the user clicks on one of those checkboxes the app starts an ActionMode context menu. But I want the application to close the ActionMode menu when clicking on another component. I tried Fragment#closeContextMenu() without success.

Any ideas how can I accomplish that?

Knowlton answered 22/6, 2012 at 15:8 Comment(0)
S
95

Whenever you are creating/starting ActionMode Create by

mMode = startActionMode(....);

To Dismiss it use following Syntax

if (mMode != null) 
 {
     mMode.finish();
 }
Sensualist answered 22/6, 2012 at 15:18 Comment(2)
Isn't there a more 'local' approach to this problem? Something without creating members?Marchpast
Note: something that got me - mMode needs to be a class field of the activity (as the naming suggests) as you can't declare it AND use it in the same callback.Erbes
G
2
actionMode.finish();

When finish method is called from actionmode ...it will destroy the action mode.

@Override
public void onDestroyActionMode(ActionMode mode) {

    //When action mode destroyed remove selected selections and set action mode to null


}

and destroy method is called from callback event

Garnett answered 22/1, 2020 at 12:19 Comment(0)
W
1

Kotlin code

Use ActionMode.Callback to finish ActionMode after menu item pressed

 private val actionModeCallbacks = object : ActionMode.Callback {
    override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
        mode.menuInflater.inflate(R.menu.menu_action_mode, menu)
        return true
    }

    override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
        return false
    }

    override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_item -> {
                mode.finish() // after click of menu item close action mode
                return true
            }
        }
        return false
    }

    override fun onDestroyActionMode(mode: ActionMode) {


    }
}

startSupportActionMode

(activity as AppCompatActivity).startSupportActionMode(actionModeCallbacks)
Winser answered 11/1, 2018 at 6:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.