Android Notes 24: How to add Back Button at Toolbar [UPDATED v2]
Updated: April 13, 2020
There are two methods to add a back button on the toolbar. First, I'm gonna show you the modern method.
Method 1 :
This little code segment let you add a back arrow ( also you can add another icon ) and gives it a click listener.
If you want to change the back button icon, you need to change R.drawable. “icon” part.
Method 2 :
Now let’s look at the old action bar method :)
First, you need to initialize the toolbar :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
then call the back button from action bar :
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Now, it is time to add a click listener :)
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
Full code from Gist :P
Method 3 : [Newest]
As the same as Method 2 at the beginning :
First, you need to initialize the toolbar :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
then call the back button from the action bar :
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
This method, we can handle the back button with onSupportNagivateUp function. Do not forget to override it!
If you have any question, please ask me :)