Enable Up/Back Button For Android Toolbar/AppBarLayout

Apr 17, 2018

The easiet way is to specify a Hierarchical Parent during activity creation (File -> New -> Activity -> Basic Activity) in Android Studio.

Android Studio New Activity

It shall create an activity declaration in AndroidManifest.xml with parentActivityName and android.support.PARENT_ACTIVITY meta-data.

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <application ...>
        ...
        <activity
            android:name=".view.DemoActivity"
            android:label="@string/title_activity_demo"
            android:parentActivityName=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.luasoftware.luapass.MainActivity" />
        </activity>
    </application>
</manifest>

The following onCreate code is generated for your activity.

class BackupActivity : AppCompatActivity() {        ...    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_backup)        setSupportActionBar(toolbar)        supportActionBar?.setDisplayHomeAsUpEnabled(true)        // supportActionBar?.setDisplayShowHomeEnabled(true)    }}

NOTE: if you didn't specify a parent activity in AndroidManifest.xml, you would need to call supportActionBar?.setDisplayShowHomeEnabled(true).

By default, the Up/Back button doesn't go back to the previous activity, but launch the parent MainActivity instead.

To override Up/Back button to go back to the previous activity, override onSupportNavigateUp to call onBackPressed.

class BackupActivity : AppCompatActivity() {
    
    ...

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }
}

If you override onOptionsItemSelected and handled android.R.id.home, then onSupportNavigateUp will not be called.

override fun onOptionsItemSelected(item: MenuItem): Boolean {    // Handle action bar item clicks here. The action bar will    // automatically handle clicks on the Home/Up button, so long    // as you specify a parent activity in AndroidManifest.xml.    return when (item.itemId) {        android.R.id.home -> {            onBackPressed()            true        }        else -> super.onOptionsItemSelected(item)    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.