0

I have a Fragment Activity hosting a Map and ListActivity. I wanna put a method when the back button is pressed on the Activity, but it seems it doesn't work at all. My Log isn't even printed on the Stacktrace. I have no idea what's wrong actually.

Here's the method:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
           Log.e("Test","Back Button Clicked");

            this.finish();
            return true;
    }
    return super.onKeyDown(keyCode, event);
}
Nishant
  • 32,082
  • 5
  • 39
  • 53
hectichavana
  • 1,436
  • 13
  • 41
  • 71

5 Answers5

2
@Override 
public void onBackPressed(){ 
  Toast.makeText(getBaseContext(), "back button pressed", Toast.LENGTH_SHORT).show(); 
  Log.e("Test","Back Button Clicked");
  this.finish();
} 
PrincessLeiha
  • 3,144
  • 4
  • 32
  • 53
hacker
  • 8,919
  • 12
  • 62
  • 108
2

If you wanted that sort of functionality you would need to override it in your activity, and then add a YourBackPressed interface to all your fragments, which you call on the relevant fragment whenever the back button is pressed.

Copied from how to implement onBackPressed() in Android Fragments?

Community
  • 1
  • 1
Shankar Agarwal
  • 34,573
  • 7
  • 66
  • 64
0

Maybe try to remove 'if' statement and see what happens?

Doszi89
  • 357
  • 2
  • 5
  • 20
0

try it , it may be works as per your need,

public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                Log.e("Test","Back Button Clicked");
    Intent backpage = new Intent(CurrentActivity.this,BackPageActivity.cls);
                    startActivity(backpage);
               CurrentActivity.this.finish();

                return true;
            }
            return super.onKeyDown(keyCode, event);    
        }
user1208720
  • 515
  • 2
  • 6
0

Problem solved:

How to implement onBackPressed() in Fragments?

In order to use the back button on a Fragment, you need to declare the onKeyDown/onBackPressed() method on your children Activities as well.

Community
  • 1
  • 1
hectichavana
  • 1,436
  • 13
  • 41
  • 71