Skip to main content

Using Toolbar In Android

Toolbar
Toolbar is used in our application as an app bar providing useful information to the user. From API level  11 ActionBar had been used as default app bar. But with newer versions and newer features ActionBar looks and behaves differently on devices depending on the version of the android it is using . So Toolbar is introduced in Android Support library to provide consistent look and behavior to our application for a wide range of devices . Toolbar is supported from API level 7 . In our application we should use

 android.support.v7.widget.Toolbar
   
This is a simple application using  Toolbar. 
Screenshots of the application are the following . 


Toolbar contains Navigation icon, Title, SubTitle and 5 menu items, on clicking any menu item a Toast will show up with menu item name.


                 
You can download the full project from the following drive link

https://drive.google.com/file/d/0BySLpWhqmbbdVU1rLWsyaUF5c2M/view?usp=sharing

                                                      OR
Download  full project from Git hub

https://github.com/arunkfedex/DemoToolbar 

1. Make sure your application is using noActionBar Themes.
    Goto values/styles.xml


<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

2.Add Toolbar to your layout file,  layout code for Toolbar is 


<android.support.v7.widget.Toolbar

        android:id="@+id/demo_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        app:theme="@style/toolbarTheme"
        app:popupTheme="@style/popupTheme"

nbsp;       />

In the Default theme Title and subtitle colors are black .So To change the color  to white i have written custom theme "toolbarThemeand "popupTheme" . Both are written in values/styles.xml 

styles.xml file 




<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="toolbarTheme" parent="ThemeOverlay.AppCompat.Light" >
        <item name="android:textColorPrimary"> @android:color/white</item>
        <item name="android:textColorSecondary">@android:color/white</item>
    </style>

    <style name="popupTheme" parent="ThemeOverlay.AppCompat.Light">
        <item name="android:textColorPrimary">@android:color/black</item>
    </style>

</resources>

activity_main.xml file


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

    <android.support.v7.widget.Toolbar
        android:id="@+id/demo_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        app:theme="@style/toolbarTheme"
        app:popupTheme="@style/popupTheme"
        />
  

</RelativeLayout>


3. Make sure your activity extends AppCompactActivity . 
 Use Toolbar in your MainActivity.java


  
public class MainActivity extends AppCompatActivity {
    Toolbar toolbar;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.demo_toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setTitle("DemoToolbar");
        toolbar.setSubtitle("hello");


4. To add menu to Toolbar. Create Menu resource directory in 
"res" directory if it is not present(res--new--Android resource directory--resource type-- menu) then create menu resource file menu_main.xml(menu--new--Menu Resource File)

menu_main.xml file


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
       android:title="Add"
       android:icon="@drawable/ic_add_white_24dp"
       android:id="@+id/add"
       app:showAsAction="always"/>
    <item
        android:title="Delete"
        android:icon="@drawable/ic_delete_white_24dp"
        android:id="@+id/delete"
        app:showAsAction="always"/>
    <item
        android:title="Settings"
        android:id="@+id/settings"
        app:showAsAction="never"/>
    <item
        android:title="Help"
        android:id="@+id/help"
        app:showAsAction="never"/>
    <item
        android:title="Exit"
        android:id="@+id/exit"
        app:showAsAction="never"/>
</menu>


5. Add menu to Toolbar and onItemClickListener to menu


toolbar.inflateMenu(R.menu.menu_main);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                String msg="";

                switch (item.getItemId()){
                    case R.id.delete:
                        msg = "delete";
                        break;
                    case R.id.add:
                        msg = "add";
                        break;
                    case R.id.settings:
                        msg = "settings";
                        break;
                    case R.id.help:
                        msg = "help";
                        break;
                    case R.id.exit:
                        msg = "exit";
                        break;


                }
                Toast.makeText(MainActivity.this,msg+" clicked",Toast.LENGTH_SHORT).show();

                return true;
            }
        });



6. Mainactivity.java  file 


package com.androidtuts4u.arun.demotoolbar;



import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.demo_toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setTitle("DemoToolbar");
        toolbar.setSubtitle("hello");
        toolbar.inflateMenu(R.menu.menu_main);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Overrid
            public boolean onMenuItemClick(MenuItem item) {
                String msg="";
                switch (item.getItemId()){
                    case R.id.delete:
                        msg = "delete";
                        break;
                    case R.id.add:
                        msg = "add";
                        break;
                    case R.id.settings:
                        msg = "settings";
                        break;
                    case R.id.help:
                        msg = "help";
                        break;
                    case R.id.exit:
                        msg = "exit";
                        break;
                }
                Toast.makeText(MainActivity.this,msg+" clicked",Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }
}


-----------------------------------NOTES------------------------------------------------

1. Always use Material Design guide lines while developing an application. use the Below link for Material Desin Guide lines
https://material.io/guidelines/material-design/introduction.html

2. Icons are downloded from
https://material.io/icons

Comments

Popular posts

Keytool is not recognized as internal or extenal command / Adding PATH in system variable

If you are running a keytool command  keytool -list -v -keystore C:\Users\arun\.android\debug.keystore -alias androiddebugkey -storepass android    and getting an error   'keytool' is not recognized as an internal or external command  If you are using any other commad like java,javac , etc.. and getting an error " is not recognized as an internal or external command"  you can also use this same steps  you are getting this error because keytool.exe , executable file which exists in the bin directory of your JDK  is not added to Path in your Environmental variables. To resolve this issue 1 .first we need to find the bin Directory of our jdk    Usually this will be in  C:\Program Files\Java\jre1.8.0_221\bin (jre1.8.0_221 - change this to your latest version , ). you can see keytool.exe file in the bin directory . (If you installed jdk in a different directory Find your Jdk installation folder and  use that path....

Simple Calculator in Android

You can view new updated simple calculator with ViemModel and LiveData in my new blog    https://androidtuts4u.blogspot.com/2021/10/simple-calculator-with-viewmodel-and.html To create a calculator first  we need to create the layout of the calculator. Layout  is created  using XML file given below <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent" >  <EditText     android:id="@+id/result_id"       android:layout_width="fill_parent"     android:layout_height="120dp"   />  <Button    android:id="@+id/Btn7_id"      android:layout_width="70dp"    android:layout_height="60dp"    android:layout_below="@id/result_id"   ...

Android Sqlite and ListView Example

This is simple application which insert data into Sqlite database --and shows the data  from the database in a ListView ListView is not used in android Anymore . We use RecyclerView and CardView   in Android RecyclerView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/04/android-recyclerview-example.html RecyclerView with CardView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/09/android-card-view-example.html This  is the first Activity of application which shows data from database in listview. Register here buton will start a Registration Activity. Submit button will add data to database and show it in the ListView of MainActivity. Update can be performed by clicking ListView items.     you can download the source code of this project from  google drive   https://drive.google.com/folderview?id=0BySLpWhqmbbdS0dtT1R2TXdBWEE&usp=sharing click on the abov...