Android – Toolbar

Now these modern days mostly android application have to use toolbar because toolbar helps to carry many shortcut functions. In this learning tutorial we learn step by step in very simple way that how to create toolbar function :-
Step 1.
Open your android studio and create new empty android project fill all required fields.
toolbar
Step 2.
After created project successfully then go to app/res/layout create one more xml file and named it toolbar.xml and paste below code.
toolbar
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
    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="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
Step 3.
Now go to activity_main file and create new include function. By this function we can involve toolbar xml file into activity_main file like below code.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">


    <include android:id="@+id/toolbar"
        layout="@layout/toolbar" /> 
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Step 4.
In this step we initialise onCreate method. Goto MainActivity.java class and paste below code. These code initialise toolbar in android application.
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }
Step 5.
Now your application is ready to debug. Open your android virtual emulator and run app to see results.
gg