If you are looking for programmatic ways of adding a back button to the Toolbar of your Android Application Activity then you are at the right place.
Tutorial Prerequisite:
- You may already have created created an Android Application by selecting a default template that displays a ToolBar.
How to add Back Button (Arrow) to Toolbar
- Open your Activity class file: Example - MainActivity.java
- Add the below lines just after super.onCreate(savedInstanceState); in the onCreate() method,
package com.example.myapplication; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.Bundle; /** * Example program to display back button * on the ToolBar on Android Activity * */ public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //To have the back button!! ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); setContentView(R.layout.activity_main); } } - Now run your App you should see the back arrow button displayed just before the Title.

✌️You would see that when you click on the back arrow button no action happens - that's because we have not written any listen for it - let's do that as well.
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(this,"Back button pressed!",Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
As the icon that's displayed is called home - we have overridden the onOptionsItemSelected method and when the home button is clicked we are displaying a toast message just to show that the functionality works. You can do the implementation as per your needs.
Happy coding :)
Have Questions? Post them here!
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!