How to use Android Actionbar as Toolbar

0
47

The toolbar was introduced in Android Lollipop(API 21) is a successor of Android Action bar. Its a View Group that can be easily placed anywhere in XML layout. Toolbar’s appearance and behavior is easily customized than the Action Bar.

Toolbar can be used for navigation in application. It can also  display activity title, icons, actions which can be triggered, additional views and other interactive items.

ToolBar Compatibility

As toolbar was introduced in Android Lollipop (API 21) hence it can be made compatible with earlier versions of android by using the appcompat-v7 support library.

There are 2 ways to add appcompat-v7 in your project.

1. In Gradle Build File – Add  compile 'com.android.support:appcompat-v7:26.0.0-alpha1' in build.gradle(Module:app) file. Here 26.0.0-alpha1 is the compat library version and 26 is the target sdk version.

2. In Project Structure -> Dependencies of Android Studio -> Add Library Dependency -> Select com.android.support:appcompat-v7:26.0.0-alpha1

 

How to Create a Toolbar

1.To create a toolbar AppTheme should not have a toolbar by default. For this change the parent of AppTheme  to “Theme.AppCompat.Light.NoActionBar” in styles.xml.

 

2.In activity_main.xml file (inside layout folder) add the below code

<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" tools:title="@string/app_name" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

3.FInal activity_main.xml file now looks like this

 

4. Now define the variable ToolBar toolbar;  in Main Activity Java Class. Add the below code in onCreate(Bundle savedInstanceState)  method of MainActivity.java.

5. Run the Emulator.

Toolbar is successfully created.

How to customize Toolbar 

Add Pop Up Menu To Toolbar

To add menu to the toolbar add a Android Resource File (menu_main) to the res folder as Menu Resource Type.

Add the below code in the main_menu.xml

Now add 2 Override methods onCreateOptionsMenu(Menu menu) and onOptionsItemSelected(MenuItem item) to MainActivity.java.

Add below code to these methods

Run  the emulator.

Add Back Button To Toolbar

To add Back Button to the action to the toolbar add getSupportActionBar().setDisplayHomeAsUpEnabled(true);  to the  onCreate(Bundle savedInstanceState)  method of MainActivity.java.  Also add  below condition to onOptionsItemSelected(MenuItem item)

Run the app in emulator.

Add Action To Toolbar

To add an action to the Toolbar add the icons in .png format of the required action in the drawable folder which is inside res folder. We have added cart.png and search.png to the drawable folder.

Add the below code to the menu_main.xml

add  below condition to onOptionsItemSelected(MenuItem item)

Run the app in the emulator

 

Files

Please let us know your thoughts on this in the comments section.