In Android Toolbar is similar to an ActionBar(now called as App Bars). Toolbar is a Viewgroup that can be placed at anywhere in the Layout. We can easily replace an ActionBar with Toolbar.
Toolbar was introduced in Material Design in API level 21 (Android 5.0 i.e Lollipop). Material Design brings lot of new features in Android that changed a lot the visual design patterns regarding the designing of modern Android applications.
An Action bar is traditionally a part of an Activity opaque window decor controlled by the framework but a Toolbar may be placed at any level of nesting within a view hierarchy. Toolbar provides more feature than ActionBar. A Toolbar may contain a combination of elements from start to end.
Important Note: Toolbar’s are more flexible than ActionBar. We can easily modify its color, size and position. We can also add labels, logos, navigation icons and other views in it. In Material Design Android has updated the AppCompat support libraries so that we can use Toolbar’s in our devices running API Level 7 and up. In AppCompat, Toolbar is implemented in the android.support.v7.widget.Toolbar class.
Table Of Contents
To use Toolbar you need to add design support library in build.gradle file.
Gradle Scripts > build.gradle (Module:App) -> inside dependencies
compile 'com.android.support:design:24.1.1' // design support Library
In Android Toolbar has more features than ActionBar and we can easily replace a ActionBar with Toolbar. In Toolbar from start to end it may contain a combination of Elements. Below we describe each and every element of Toolbar.
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark"> </android.support.v7.widget.Toolbar>
We can easily replace ActionBar with Toolbar by using setSupportActionBar() method. Here is the code of replacing ActionBar with Toolbar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar
Now let’s we discuss some common attributes of a Toolbar that helps us to configure it in our layout (xml).
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/toolbar" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark"> </android.support.v7.widget.Toolbar>
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" app:logo="@drawable/logo"><!-- logo for the Toolbar--> </android.support.v7.widget.Toolbar>
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" app:logo="@drawable/logo" app:logoDescription="LOGO"><!-- logo and logo description for the Toolbar--> </android.support.v7.widget.Toolbar>
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" app:navigationIcon="@drawable/logo"><!-- navigation icon for the Toolbar--> </android.support.v7.widget.Toolbar>
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" app:navigationContentDescription="Navigation Description" app:navigationIcon="@drawable/logo"> <!-- navigation icon and description for the Toolbar--> </android.support.v7.widget.Toolbar>
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" app:title="AbhiAndroid"> <!-- title for the Toolbar--> </android.support.v7.widget.Toolbar>
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" app:titleTextColor="#F00" app:title="AbhiAndroid"> <!-- title text color for the Toolbar--> </android.support.v7.widget.Toolbar>
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" app:subtitle="AbhiAndroid"> <!-- sub title for the Toolbar--> </android.support.v7.widget.Toolbar>
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" app:subtitle="AbhiAndroid" app:subtitleTextColor="#F00"> <!-- sub title text color for the Toolbar--> </android.support.v7.widget.Toolbar>
Let’s we discuss some important methods of Toolbar that may be called in order to add Action icons manage the Toolbar.
Important Note: To understand below functions of Toolbar properly please do read 2nd example in this article.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar toolbar.setLogo(R.drawable.logo); // setting a logo in toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar toolbar.setLogo(getResources().getDrawable(R.drawable.logo)); // setting a logo in toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar toolbar.setLogo(getResources().getDrawable(R.drawable.logo)); // setting a logo in toolbar Drawable drawableLogo=toolbar.getLogo(); // get the drawable logo from Toolbar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar toolbar.setLogo(getResources().getDrawable(R.drawable.logo)); // setting a logo in toolbar toolbar.setLogoDescription("LOGO"); // set description for the logo getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar toolbar.setLogo(getResources().getDrawable(R.drawable.logo)); // setting a logo in toolbar toolbar.setLogoDescription(getResources().getString(R.string.descrition)); // set description for the logo getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar toolbar.setLogo(getResources().getDrawable(R.drawable.logo)); // setting a logo in Toolbar toolbar.setLogoDescription("LOGO"); // set description for the logo CharSequence logoDescription=toolbar.getLogoDescription(); // get the logo description from Toolbar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar toolbar.setNavigationIcon(R.mipmap.ic_launcher); // set icon for navigation button getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.logo)); // setting a navigation icon in Toolbar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.logo)); // setting a navigation icon in Toolbar Drawable navigationIcon = toolbar.getNavigationIcon(); // get navigation icon from Toolbar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar4 toolbar.setTitle(getResources().getString(R.string.title)); // setting a title for this Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar4 toolbar.setTitle("AbhiAndroid"); // setting a title for this Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar4 toolbar.setSubtitle(getResources().getString(R.string.subTitle)); // setting a sub title for this Toolbar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar4 toolbar.setSubtitle("AbhiAndroid"); // setting a sub title for this Toolbar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar4 toolbar.setTitle("AbhiAndroid"); // setting a title for this Toolbar CharSequence title=toolbar.getTitle(); // get the displayed title from Toolbar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar4 toolbar.setSubtitle("AbhiAndroid"); // setting a sub title for this Toolbar CharSequence title=toolbar.getSubtitle(); // get the displayed sub title from Toolbar. getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar toolbar.setNavigationIcon(R.drawable.logo); // set icon for navigation button toolbar.setNavigationContentDescription("Navigation"); // setting description for navigation button
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar toolbar.setNavigationIcon(R.drawable.logo); // set icon for navigation button toolbar.setNavigationContentDescription(getResources().getString(R.string.description)); // setting description for navigation button.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar toolbar.setNavigationIcon(R.drawable.logo); // set icon for navigation button toolbar.setNavigationContentDescription("Navigation"); // setting description for navigation button CharSequence description=toolbar.getNavigationContentDescription(); // get navigation button description
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar toolbar.setTitle("AbhiAndroid"); // setting a title for this Toolbar toolbar.setTitleTextColor(Color.RED); // set title text color for Toolbar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar toolbar.setSubtitle("AbhiAndroid"); // setting a sub title for this Toolbar toolbar.setSubtitleTextColor (Color.RED); // set sub title text color for Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the current title from the Toolbar // implement setNavigationOnClickListener event toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // add code here that execute on click of navigation button } });
Below is the first example of Toolbar in which we create a Toolbar and replace it with ActionBar. In this examle we add action icons in Toobar and on click of navigation Button of Toolbar we open a Navigation Drawer. In our main layout we use Drawer Layout and Navigation View. Drawer Layout is the root layout in which we include a Toolbar and also define a FrameLayout and a Navigation View. In Navigation View we set the items from menu file and FrameLayout is used to replace the Fragments on the click of menu items. Whenever a user click on menu item, Fragment is replaced according to menu item’s id and a toast message with menu item title is displayed on the screen. We also create three Fragments that should be replaced on click of menu items
Step 1: Create a new project and name it ToolbarExample.
Step 2: Open Gradle Scripts > build.gradle and add Design support library dependency. If you are on the latest version of Android Studio you don’t need to add a compiled dependency for Appcombat v7 21 library if not then please make sure you add the line below in your gradel build dependencies.
apply plugin: ‘com.android.application’
android { compileSdkVersion 24 buildToolsVersion "24.0.1" defaultConfig { applicationId "abhiandroid.toolbarexample" minSdkVersion 16 targetSdkVersion 24 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.1.1' compile 'com.android.support:design:24.1.1' // design support Library }
Step 3: ActionBars are replaced with Toolbar so we can still use ActionBar but in our example we are going to make a Toolbar so go to your style.xml file and change the theme to “Theme.AppCompat.Light.NoActionBar” This theme helps us get rid of the ActionBar so we can make a Toolbar.
<!-- 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> </resources>
Step 4: Now let’s talk about the color scheme for our application. Open your color.xml file from values folder. In this XML file colorPrimary is the primary color for the app and colorPrimaryDark color is the color of the status bar. We can easily change our colors from this file.
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> </resources>
Step 5: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we define a DrawerLayout that is the parent layout in which we include a toolbar.xml file and also define a FrameLayout and a Navigation View. In Navigation View we set the items from menu file named “nav_items” and FrameLayout is used to replace the Fragments on the click of menu items.
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- include your toolbar layout--> <include layout="@layout/toolbar" /> <!-- Let's add fragment --> <FrameLayout android:id="@+id/frame" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> <!-- Navigation view to show the menu items --> <android.support.design.widget.NavigationView android:id="@+id/navigation" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:menu="@menu/nav_items" /> </android.support.v4.widget.DrawerLayout>
Step 6: Open res -> menu -> nav_items.xml and add following code. Here we define the menu items.
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkableBehavior="single"> <!-- Add menu items here Menu items with icon and Title --> <item android:id="@+id/first" android:icon="@mipmap/ic_launcher" android:title="First Menu" /> <item android:id="@+id/second" android:icon="@mipmap/ic_launcher" android:title="Second Menu" /> <item android:id="@+id/third" android:icon="@mipmap/ic_launcher" android:title="Third Menu" /> </group> </menu>
Step 7: Now create a xml layouts by right clicking on res/layout -> New -> Layout Resource File and name it toolbar.xml
In this file we set the background color, navigation button and tilte for the Toolbar.
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" app:navigationIcon="@drawable/menu_icon" app:title="AbhiAndroid" app:titleTextColor="#FFF"> <!-- navigation button and title for the Toolbar--> </android.support.v7.widget.Toolbar>
Step 8: Open src -> package -> MainActivity.java
In this step we open the MainActivity and add the code for initiates the views(DrawerLayout, Toolbar,NavigationView and other views). In this we replace the ActionBar with our ToolBar by using setSupportActionBar() method and then implment setNavigationOnClickListener event and add the code to open the drawer on click of navigation button. After that we implement setNavigationItemSelectedListener event on NavigationView so that we can replace the Fragments according to menu item’s id and a toast message with menu item’s title is displayed on the screen. In this I have added comments in code to help you to understand the code easily so make you read the comments.
package abhiandroid.toolbarexample; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity { DrawerLayout dLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar // implement setNavigationOnClickListener event toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dLayout.openDrawer(Gravity.LEFT); } }); setNavigationDrawer(); // call method } private void setNavigationDrawer() { dLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // initiate a DrawerLayout NavigationView navView = (NavigationView) findViewById(R.id.navigation); // initiate a Navigation View // implement setNavigationItemSelectedListener event on NavigationView navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { Fragment frag = null; // create a Fragment Object int itemId = menuItem.getItemId(); // get selected menu item's id // check selected menu item's id and replace a Fragment Accordingly if (itemId == R.id.first) { frag = new FirstFragment(); } else if (itemId == R.id.second) { frag = new SecondFragment(); } else if (itemId == R.id.third) { frag = new ThirdFragment(); } // display a toast message with menu item's title Toast.makeText(getApplicationContext(), menuItem.getTitle(), Toast.LENGTH_SHORT).show(); if (frag != null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frame, frag); // replace a Fragment with Frame Layout transaction.commit(); // commit the changes dLayout.closeDrawers(); // close the all open Drawer Views return true; } return false; } }); } }
Step 9: Now we need 3 fragments and 3 xml layouts. So create three fragments by right click on your package folder and create classes and name them as FirstFragment, SecondFragment and ThirdFragment and add the following code respectively.
FirstFragment.class
package abhiandroid.toolbarexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FirstFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_first, container, false); } }
SecondFragment.class
package abhiandroid.toolbarexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SecondFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_second, container, false); } }
ThirdFrament.class
package abhiandroid.toolbarexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ThirdFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_third, container, false); } }
Step 10: Now create 3 xml layouts by right clicking on res/layout -> New -> Layout Resource File and name them as fragment_first, fragment_ second and fragment_third and add the following code in respective files.
Here we will design the basic simple UI by using TextView in all xml’s.
fragment_first.xml
<FrameLayout 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" tools:context="abhiandroid.toolbarexample.FirstFragment"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="First Fragment" android:textSize="25sp" /> </FrameLayout>
fragment_second.xml
<FrameLayout 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" tools:context="abhiandroid.toolbarexample.SecondFragment"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Second Fragment" android:textSize="25sp" /> </FrameLayout>
fragment_third.xml
<FrameLayout 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" tools:context="abhiandroid.toolbarexample.ThirdFragment"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Third Fragment" android:textSize="25sp" /> </FrameLayout>
Output:
Now run the App and you will see Menu icon and “AbhiAndroid” text written at the top which is created using Toolbar. Now click on menu and three items inside it will be shown. Now click on any of them and corresponding to it layout will open up.
Below is the simple example of Toolbar in which we create a Toolbar and replace it with our ActionBar. In this example we set Logo, title and menu for Toolbar. In our main layout we create a Toolbar and in Activity get the reference of Toolbar and set the title and logo on it. In this we use Activity’s overrided method onCreateOptionsMenu to set the menu items from menu file and onOptionsItemSelected to set click listeners on menu item’s. On click of menu item the title of menu is displayed on the screen with the help of Toast.
Step 1: Create a new project and name it SimpleToolbarExample.
Step 2: Open Gradle Scripts > If you are on the latest version of Android Studio you don’t need to add a compiled dependency for Appcombat v7 21 library if not then please make sure you add the line below in your gradel build dependencies.
apply plugin: 'com.android.application' android { compileSdkVersion 24 buildToolsVersion "24.0.1" defaultConfig { applicationId "abhiandroid.com.simpletoolbarexample" minSdkVersion 16 targetSdkVersion 24 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.1.1' }
Step 3: ActionBars are replaced with Toolbar so we can still use ActionBar but in our example we are going to make a Toolbar so go to your style.xml file and change the theme to “Theme.AppCompat.Light.NoActionBar” This theme helps us get rid of the ActionBar so we can make a Toolbar.
<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> </resources>
Step 4: Now let’s talk about the color scheme for our application. Open your color.xml file from values folder. In this XML file colorPrimary is the primary color for the app and colorPrimaryDark color is the color of the status bar. We can easily change our colors from this file.
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> </resources>
Step 5: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we define a Toolbar in our main XML file and set it’s background color and theme.
<?xml version="1.0" encoding="utf-8"?> <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" tools:context="abhiandroid.com.simpletoolbarexample.MainActivity"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" /> </RelativeLayout>
Step 6: Open res -> menu -> menu_main.xml and add following code:
In this step we create 3 menu items that will be displayed on Toolbar.
<menu 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" tools:context=".MainActivity"> <!-- Menu item's that displayed on Toolbar. --> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="@string/action_settings" app:showAsAction="never" /> <item android:id="@+id/action_search" android:icon="@drawable/ic_search" android:orderInCategory="200" android:title="Search" app:showAsAction="ifRoom" /> <item android:id="@+id/action_user" android:icon="@drawable/user" android:orderInCategory="300" android:title="User" app:showAsAction="ifRoom" /> </menu>
Step 7: Open src -> package -> MainActivity.java
In this step we open the MainActivity and add the code for initiates the Toolbar.. In this we replace the ActionBar with our ToolBar by using setSupportActionBar() method and also set the tiltle and logo for the Toolbar. After that we implement Activity’s overrided method onCreateOptionsMenu to set the menu items from menu file and onOptionsItemSelected to set click listeners on menu item’s. On click of menu item the tiltle of menu is displayed on the screen with the help of Toast. In this I have added comments in code to help you to understand the code easily so make sure you read the comments.
package abhiandroid.com.simpletoolbarexample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar toolbar.setTitle("AbhiAndroid"); // set Title for Toolbar toolbar.setLogo(R.drawable.android); // set logo for Toolbar setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar } // Activity's overrided method used to set the menu file @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } // Activity's overrided method used to perform click events on menu items @Override public boolean onOptionsItemSelected(MenuItem item) { // 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. int id = item.getItemId(); //noinspection SimplifiableIfStatement // Display menu item's title by using a Toast. if (id == R.id.action_settings) { Toast.makeText(getApplicationContext(), "Setting Menu", Toast.LENGTH_SHORT).show(); return true; } else if (id == R.id.action_search) { Toast.makeText(getApplicationContext(), "Search Menu", Toast.LENGTH_SHORT).show(); return true; } else if (id == R.id.action_user) { Toast.makeText(getApplicationContext(), "User Menu", Toast.LENGTH_SHORT).show(); return true; } return super.onOptionsItemSelected(item); } }
Output:
Now run the App and you will see Toolbar at the top. Click on it and message created using Toast will be displayed.
Premium Project Source Code: