0

I've an Activity that extends AppCompatActivity.

I tried to disable back button like this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
    }
    return true;
}

@Override
public void onBackPressed() {
    Toast.makeText(this, "Back pressed", Toast.LENGTH_LONG).show();
}

I get the Toast which is good sign, but bad sign is, that it finishes activity and goes to the previous one (I'd like to avoid that).

MaaAn13
  • 1,008
  • 3
  • 18
  • 46

2 Answers2

0

If you use onBackPressed then remove onKeyDown for now. Read onKeyDown() or onBackPressed().

FYI

Remove this method

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
    }
    return true;
}

Just use

@Override
public void onBackPressed() 
{
  //super.onBackPressed();
}
IntelliJ Amiya
  • 73,189
  • 14
  • 161
  • 193
0

Override the onBackPressed in the Activity:

@Override
    public void onBackPressed() {
        backButtonHandler();
        return;
    }

Write your code within the method called in onBackPressed()

 public void backButtonHandler() {
    Toast.makeText(this, "Back pressed", Toast.LENGTH_LONG).show();
}
kgandroid
  • 5,459
  • 5
  • 37
  • 68