Belgi
Belgi

Reputation: 15052

Android back button

In my app I have a button that if the user clicks than a text box appears on the screen (I use the setVisibility from GONE to VISIBILE). the problem I have is when the user presses the BACK button on the device : it closes my app.

Is there any way that when the user presses the BACK button than my code will be called (so I can set the visibility to GONE) ?

Upvotes: 0

Views: 345

Answers (3)

Laurent'
Laurent'

Reputation: 2631

The following works since API level 1:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        //Do whatever you want 
        //AND 
        //return true to tell the framework you did handle the back key
        return true;
    }
    //This is not the back key, just ask the framework to behave as usual.
    return super.onKeyDown(keyCode, event);
}

Starting from API level 5 (android 2.0) you can also use:

@Override
public void onBackPressed() {
    // Do something (or nothing) here
    return;
}

See this android developer blog message for a complete overview.

Upvotes: 1

Arpit Garg
Arpit Garg

Reputation: 8546

public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Put your code here
        }

        return true;

    }

Upvotes: 0

user658042
user658042

Reputation:

Override onBackPressed() with your desired functionality.

The default implementation just calls finish() to close the current activity.

Upvotes: 1

Related Questions