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 - MainActivity.java
  2. 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);
        }
    }
  3. Now run your App you should see the back arrow button displayed just before the Title.
Output:
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.

    @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!



Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.