vishalaksh
vishalaksh

Reputation: 2154

what is the code for the default action of the 'back' button in android?

I have an edittext and a save button displayed. When back key is pressed, I want them to be gone (if they are visible) and the next back press will do the default action of the back button. The code is as follows:

public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            event.startTracking();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
                && !event.isCanceled()) {
            if(save.isShown())
            {
                 save.setVisibility(Button.GONE);
                 text.setVisibility(EditText.GONE);
            }
                    //else ???????????????

            return true;
        }
        return super.onKeyUp(keyCode, event);
    }   

The above code has following outcomes: 1. when edittext and button is visible, then back button makes them gone but the following press renders nothing. Although if back button is kept pressed, we go back to the previous activity. 2. when edittext and button are initially not there, pressing of back button stops the application unexpectedly.Although if back button is kept pressed, we go back to the previous activity.

In the place of else, I have tried finish() but the program is stopping unexpectedly. return false also results same..

Upvotes: 3

Views: 9831

Answers (3)

Codeman
Codeman

Reputation: 12375

@Override
public void onBackPressed() {
    myMethod();
    super.onBackPressed();
}

It's very important to call the supermethod when you override methods like this. Put any code you want to execute before the supermethod call and you should be golden!

EDIT:

before the supercall, not after.

Upvotes: 1

zeonic
zeonic

Reputation: 383

@Override
public void onBackPressed() {
  doStuff();
}

Link Here

Edit

Wait, what about a long press? If I'm reading the original question correctly you want the initial back press to hide some views, and the second to behave normally? Why not just something like this:

private boolean flag = false;

@Override
public void onBackPressed() {
  if(flag) {
    super.onBackPressed();
  } else {
    view.setVisibility(View.GONE);
    flag = true;
  }
}

Upvotes: 5

njzk2
njzk2

Reputation: 39406

replace

if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
            && !event.isCanceled()) {
    if(save.isShown()) {

by

if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
            && !event.isCanceled() && save.isShown()) {

Upvotes: 1

Related Questions