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
  • 264
  • 5
  • 24
  • 54

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
  • 74,896
  • 15
  • 165
  • 198
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,507
  • 5
  • 39
  • 69