Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override UP button in action bar

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?

like image 313
Yoh Hendry Avatar asked Jun 06 '15 05:06

Yoh Hendry


2 Answers

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);
}
like image 84
Anggrayudi H Avatar answered Sep 29 '22 11:09

Anggrayudi H


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);
}
like image 33
Dasser Basyouni Avatar answered Sep 29 '22 10:09

Dasser Basyouni