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
333 views
in Technique[技术] by (71.8m points)

android - Prevent to cancel Action Mode by press back button

Action mode started by calling getActivity().startActionMode(calback); is automatically canceled after back button pressed. Is possible avoid this behavior? I need to do another operation after back button was pressed in some situation during action mode.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is an interesting problem. When the ActionMode is active the back key event is consumed internally. The event is not propagated to either onBackPressed() or onKeyUp(int keyCode, KeyEvent event) callbacks.

Fortunately, you can use dispatchKeyEvent(KeyEvent event) which is still called.

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if(mActionModeIsActive) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
           // handle your back button code here
           return true; // consumes the back key event - ActionMode is not finished
        }
    }
    return super.dispatchKeyEvent(event);
}

You might wonder what will be the behavior in case you have a submenu in the ActionMode and you close it with the back key. In this case dispatchKeyEvent() is not called so you can safely use the code.

The above code works also with ActionBarSherlock. The only problem I found is on Android 3.1 device when the native ActionMode is used, in this case the dispatchKeyEvent() is not called. Use ActionBarSherlock's ActionMode to solve it.


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

...