Search code examples
androidandroid-actionbar

How to add the back arrow in the action bar?


I was wondering how I could add this arrow in the action bar. I have already an action bar but can only add icons at the right hand side and is it possible to center the label?

enter image description here


Solution

  • First, you'd have to define the parent Activity for the one you'd like to display back button in. You do this via the manifest.

    Do this in your AndroidManifest.xml somewhere within the application tag:

    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
    

    That done, all you'd need to do is to call this on your target Activity, right within its onCreate() method:

    getActionBar().setDisplayHomeAsUpEnabled(true);
    

    ..or, if you happen to use AppCompat library in your project:

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    

    You can refer to the official docs for up navigation here for further details.