Friday, March 6, 2015

Detect / Capture back key on Activity

Although it's advised to let the OS handle back key press, here's how you can detect back key press on activity.
Override the onKeyDown method of your Activity class as follows:
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            // Back button was pressed
            // Do some work
            if (mViewFlipper.getDisplayedChild() != 0) {
                mViewFlipper.showPrevious();
                // Return true
                return true;
            }
        }
        // Else let super handle the event
        return super.onKeyDown(keyCode, event);
    }

No comments:

Post a Comment