Android Custom Toolbar Back Button Example kotlin

07-Jan-2025

Android Custom Toolbar Back Button Example kotlin

Output:




1/  Modify the acitvity_main.xml file.



<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/customToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:title="Custom Toolbar"
app:navigationIcon="@drawable/baseline_arrow_back_ios_new_24"
app:titleTextColor="@android:color/white" />
</com.google.android.material.appbar.AppBarLayout>

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Custom Toolbar Example"
android:textSize="18sp" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>



2/  Modify the MainActivity.kt file.



package com.microappvalley.androidcustomtoolbarbackbuttonexamplekotlin

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.appbar.MaterialToolbar

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val toolbar: MaterialToolbar = findViewById(R.id.customToolbar)
setSupportActionBar(toolbar)

supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)

toolbar.setNavigationOnClickListener {
Toast.makeText(this@MainActivity, "Back button clicked", Toast.LENGTH_SHORT).show()
finish()
}
}
}





Comments