How to add Back Button on Toolbar in Android [Tutorial]

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

  1. Open your Activity class file: Example -
  2. Add the below lines just after super.onCreate(savedInstanceState); in the onCreate() method,
    package com.example.myapplication;
    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 {
        protected void onCreate(Bundle savedInstanceState) {
            //To have the back button!!
            ActionBar actionBar = getSupportActionBar();
  3. Now run your App you should see the back arrow button displayed just before the Title.
Android Toolbar Back Button Example
Android Toolbar Back Button Example

✌️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.

    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {


                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!
Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap