Override the UP button in the action bar

I would like to avoid breaking parental activity whenever I clicked <in the action bar.

which method is called from AppCompatActivity when we click this button?

Is there a way to override it? and is there a way to override all actions?

+5
source share
2 answers

I would like to avoid breaking parental activity whenever I clicked <in the action bar.

Your parent activity will be paused as soon as you press this button, instead of destroying it.

Is there a way to override it? and is there a way to override all actions?

Just call:

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

You need to call it for the actions you want to override. There is no other way to call it "once for all."

which method is called from AppCompatActivity when we click this button?

By default, there is no method in it. If you use the Toolbar , call setNavigationOnClickListener() to do something when this button is clicked.

  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 an ActionBar , this button will be available on the 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); } 
+11
source

For those who are looking to override the up button, to be the same as the back button, and go from operation to another correctly, just override

 @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home){ onBackPressed(); return true; } return super.onOptionsItemSelected(item); } 
+1
source

All Articles