Activity does not close when you click the back button of the toolbar

Refer to the image below. enter image description here
I want to return to previous activities.
But when you click the back button on the toolbar, nothing happens.
I used the following code to achieve what was unlucky yet.

public boolean onOptionsItemSelected(MenuItem item){ if(item.getItemId() == R.id.home) { finish(); } return true; } 
+5
source share
3 answers
 @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { // Respond to the action bar Up/Home button case android.R.id.home: //NavUtils.navigateUpFromSameTask(this); onBackPressed(); return true; } return super.onOptionsItemSelected(item); } 
+11
source

In your OnCreate method

  toolbar.setTitle(R.string.title_activity_setting); setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

In your onOptionsItemSelected method

 public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } 

I will work.

+2
source

Add the onBackPressed() method to your activity. And super this. And when you click the back button on this.onBackPressed() . Update code for this:

 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { super.onBackPressed(); } 
0
source

All Articles