Saku
Saku

Reputation: 119

Android 'Back' button action

Can i assign the action of the default Android 'Back' button into another button? I mean without having to write the code, is there a predefined 'Back' method?

Thanks!

Upvotes: 6

Views: 16990

Answers (2)

Thkru
Thkru

Reputation: 4199

There are two ways for your purpose:

1st: Override the onBackPressed method in your Activty:

@Override
    public void onBackPressed()
    {
        super.onBackPressed();
    }


2nd: Override onKeyDown and look for KeyEvent.KEYCODE_BACK

public boolean onKeyDown(int keyCode, KeyEvent event){
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {

        }
        return false;
    }


If you want to combine both (lets say you want the backAction on the menuButton, It'll look like this:

public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_MENU)
        {
                onBackPressed();
        }
        return false;
    }

Upvotes: 5

Samir Mangroliya
Samir Mangroliya

Reputation: 40406

onClick of Button add onBackPressed();

public void onClick(){

  onBackPressed();

}

Upvotes: 16

Related Questions