0

I have an activity that when the user press back arrow doing some thing. When you press the back button on the phone, it does the finish () method, but it doesn't happen when you press the back arrow. How to fix it?

I'm sorry for the grammatical errors. I would be happy if you remind me of the bad ones.

  • 2
    On back arrow click call this function `super.onBackPressed()` – Jignesh Mayani Sep 04 '19 at 08:37
  • Possible duplicate of [Android - How To Override the "Back" button so it doesn't Finish() my Activity?](https://stackoverflow.com/questions/3141996/android-how-to-override-the-back-button-so-it-doesnt-finish-my-activity) – peco Sep 04 '19 at 08:39
  • add your code of `onBackPressed()` method – Manohar Sep 04 '19 at 08:47

2 Answers2

0

are you looking for

Xamarin.Android:

public override void OnBackPressed()
{
    // do something on backbutton pressed
}

Java:

@Override
public void onBackPressed()
{
     // code here to show dialog
     super.onBackPressed();  // optional depending on your needs
}
Aiko West
  • 791
  • 1
  • 10
  • 30
0

If you want the same behavior for the back button. Add this code.

Java Code

 @Override
 public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        YourActivity.this.onBackPressed();
    }
    return super.onOptionsItemSelected(item);
}

Kotlin Code

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if (item.itemId == android.R.id.home) {
        this@YourActivity.onBackPressed()
    }
    return super.onOptionsItemSelected(item)
}
Muhammad Farhan
  • 1,113
  • 10
  • 22