info@androidpaper.co.in

ToolBar in Android with Example

In Android development using Kotlin, you can create a toolbar using the Toolbar widget provided by the Android framework. The Toolbar widget is a versatile and customizable app bar that can be used to display various UI components, such as a title, navigation buttons, and actions. Here's how you can create a toolbar in an Android app using Kotlin:

Make sure to include the necessary dependencies in your app's build.gradle file to ensure that the Toolbar and other AndroidX components are available:

implementation 'androidx.appcompat:appcompat:1.3.1'
implementation ‘com.google.android.material:material:1.2.1’

Open your layout XML file (e.g., activity_main.xml) and add the Toolbar widget:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- Other layout components -->

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</RelativeLayout>

In your MainActivity.kt file (or any other activity where you want to use the toolbar), set up the toolbar in the onCreate method:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.widget.Toolbar

class MainActivity : AppCompatActivity() {

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

        val toolbar: Toolbar = findViewById(R.id.my_toolbar)
        setSupportActionBar(toolbar) // Set the toolbar as the app bar

        supportActionBar?.apply {
            title = "My Toolbar" // Set the title of the toolbar
            setDisplayHomeAsUpEnabled(true) // Enable the back button
            // Other customization options for the action bar
        }
    }
}

Remember to customize the toolbar's appearance and behavior according to your app's requirements by adjusting attributes like background color, title, navigation buttons, and action items. Be sure to check for any updated dependencies and guidelines as the Android ecosystem evolves.