How to call a method when back button in emulator pressed

1.2k Views Asked by At

I use below code for my ActionBar Button, it can back to previous Activity and also display the Toast.

 case android.R.id.home:
 Toast.makeText(getApplication(),"A",Toast.LENGTH_SHORT).show();
 onBackPressed();
 return true;

If I press back in my emulator, no Toast display. So I decide to add this

 public void onBackPressed()
    {
        Toast.makeText(getApplication(),"A",Toast.LENGTH_SHORT).show();
        return;
    }

After added this, when I press the back button in the emulator, it to display Toast but not returning to previous Activity. I click the ActionBar Button, same thing happened.

4

There are 4 best solutions below

0
On BEST ANSWER

Try to run super method :

    public void onBackPressed()
    {
        super.onBackPressed();
        Toast.makeText(getApplication(),"A",Toast.LENGTH_SHORT).show();
    }

It will call normal back press, and shows Toast

0
On

I would implement a dialog asking the user if they wanted to exit and then call super.onBackPressed() if they did.

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("Really Exit?")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes, new OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                WelcomeActivity.super.onBackPressed();
            }
        }).create().show();
}

In the above example, you'll need to replace WelcomeActivity with the name of your activity.

0
On

you have to override onBackPressed() method and then put your Toast there

@Override
public void onBackPressed()
{
    super.onBackPressed();
    Toast.makeText(getApplication(),"A",Toast.LENGTH_SHORT).show();      
}
0
On

Remove this code

case android.R.id.home:
    Toast.makeText(getApplication(),"A",Toast.LENGTH_SHORT).show();
    onBackPressed();
    return true;

And just Use this override Method

@Override
public void onBackPressed()
{
    super.onBackPressed()
    Toast.makeText(getApplication(),"A",Toast.LENGTH_SHORT).show();
}

It will called by android itself when you press back button. you not need to call it yourslef.