Override UP button in action bar
Asked Answered
N

2

7

i'd like to avoid parent activity being destroyed whenever i clicked < button in action bar.

which method is being called from AppCompatActivity when we press that button?

is there a way for me to override it? and is there a way to override for all activities?

Nailbiting answered 6/6, 2015 at 5:6 Comment(0)
D
15

i'd like to avoid parent activity being destroyed whenever i clicked < button in action bar.

Your parent activity will be paused once you press that button, instead of gets destroyed.

is there a way for me to override it? and is there a way to override for all activities?

Just call:

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

You need to call it to activities you want to override the button. There's no other option to call it 'once for all'.

which method is being called from AppCompatActivity when we press that button?

By default, there's no method in it. If you use Toolbar, call setNavigationOnClickListener() to do something when that button is pressed.

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // do something here, such as start an Intent to the parent activity.
        }
    });

If you use ActionBar, that button will be available on Menu:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        // do something here, such as start an Intent to the parent activity.
    }
    return super.onOptionsItemSelected(item);
}
Donalt answered 6/6, 2015 at 7:26 Comment(1)
If you set the click listener on the toolbar, it will no longer return to the parent unless you call something equivalent to NavUtils.navigateUpFromSameTask in the listener.Kampong
T
12

For those who are searching to override the up button to be the same as the back button and navigate from activity to another correctly, simply override

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home){
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
Tighe answered 17/11, 2017 at 1:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.