A Toolbar widget is a generalization of action bar so it allows us to customize the way we want and then place it like any other widget, at any level of nesting with the view hierarchy.
In this article, we will see how to add a toolbar to our layout.
So when should we use a toolbar?
Toolbar Usage
Use a Toolbar when you want to have more control over the features that an action bar provides. For example,
- If you want to have more control over its theme.
- If you want to place toolbar at any arbitrary level of nesting within the view hierarchy.
- If you want to show multiple toolbars on the screen.
Adding Toolbar Widget
Toolbar is represented by class android.support.v7.widget.Toolbar
and is a part of AppCompat framework. and has feature and API parity with the framework widget.
In order to use it, first add compile 'com.android.support:appcompat-v7:23.0.1'
to gradle dependencies section.
build.gradle:
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.javarticles.android" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.0.1' }
We want to replace action bar with our custom toolbar widget. Your app theme should extend from Theme.AppCompat.NoActionBar
or the light variant.
styles.xml:
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> </style> <style name="Theme.Javarticles" parent="@style/Theme.AppCompat.Light.NoActionBar"> <item name="android:windowBackground">@color/white</item> <item name="colorPrimary">@color/primary_color</item> <item name="colorPrimaryDark">@color/primary_color_dark</item> <item name="colorAccent">@color/accent_color</item> <item name="colorControlHighlight">@color/highlight_color</item> </style> <style name="Theme.AppCompat.Light.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> </resources>
Now we will include the Toolbar widget in the layout XML. Open the layout file of your main activity (activity_main.xml) and add the toolbar using tag.
activity_main.xml:
<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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <android.support.v7.widget.Toolbar android:id="@+id/my_toolbar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:background="#2196F3" android:minHeight="?actionBarSize" android:theme="@style/ThemeOverlay.AppCompat.ActionBar"> <TextView android:id="@+id/toolbar_title" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_vertical" android:text="@string/home" android:textColor="@color/primary_text_color" android:textSize="@dimen/toolbar_title_textsize"/> </android.support.v7.widget.Toolbar> <FrameLayout android:id="@+id/container" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@id/my_toolbar" /> </RelativeLayout>
The main layout contains toolbar and a fragment which we replace with the main content. Our main content is a simple text field.
content.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/content" android:textSize="45.0sp" /> </RelativeLayout>
In the toolbar, we want to add a search item and a cart item. This will do it using the menu layout.
Once the icon is imported, open menu_main.xml located under res ⇒ menu and add the search menu item as mentioned below.
main_menu.xml:
<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"> <item android:icon="@drawable/ic_search" android:id="@+id/action_search" android:title="@string/title_search" app:showAsAction="collapseActionView|ifRoom" app:actionViewClass="android.support.v7.widget.SearchView" /> <item android:icon="@drawable/ic_cart" android:id="@+id/action_cart" android:title="@string/title_cart" app:showAsAction="always" /> <item android:id="@+id/action_settings" android:title="@string/action_settings" android:orderInCategory="100" app:showAsAction="never" /> </menu>
You also need the searchable XML, this will help the android framework to know your search configurations. For example, the search hint.
searchable.xml:
<?xml version="1.0" encoding="utf-8"?> <searchable android:label="@string/app_name" android:hint="@string/search_hint" xmlns:android="http://schemas.android.com/apk/res/android" />
Our main activity will extend the activity from AppCompatActivity
.
Since we want the toolbar to replace the action bar, we will have to find the toolbar and call setSupportActionBar() method to replace the action bar.
In onCreateOptionsMenu()
, we will inflate the menu XML to add items to the action bar which is now represented by our toolbar.
In onOptionsItemSelected
, we will handle the action bar item clicks.
MainActivity:
package com.javarticles.android; import android.app.ActivityManager; import android.os.Build; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class MainActivity extends ActionBarActivity { private TextView mTitleView; private Toolbar mToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.mToolbar = ((Toolbar)findViewById(R.id.ul_toolbar)); this.mTitleView = ((TextView)findViewById(R.id.toolbar_title)); setSupportActionBar(this.mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayUseLogoEnabled(false); this.mTitleView.setText(getString(R.string.home)); if (Build.VERSION.SDK_INT >= 21) { setTaskDescription(new ActivityManager.TaskDescription(getString(R.string.home))); } supportInvalidateOptionsMenu(); getSupportFragmentManager().beginTransaction().replace(R.id.container, new ContentFragment(), "com.javarticles.android.Home").commitAllowingStateLoss(); } @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; } @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 if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
We will replace the fragment R.id.container
with content fragment using the below code:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new ContentFragment(), "com.javarticles.android.Home").commitAllowingStateLoss();
Here is the content fragment.
ContentFragment:
package com.javarticles.android; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ContentFragment extends Fragment { public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) { return paramLayoutInflater.inflate(R.layout.content, paramViewGroup, false); } }
colors.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="primary_color">#ffffffff</color> <color name="primary_color_dark">#ffbdbdbd</color> <color name="accent_color">#ff9e9e9e</color> <color name="highlight_color">#ffdadada</color> <color name="primary_text_color">#ff48484a</color> <color name="white">#ffffffff</color> </resources>
strings.xml:
<resources> <string name="app_name">Android Toolbar Example</string> <string name="home">Home</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="search_hint">Search Javarticles</string> <string name="title_search">Search</string> <string name="title_cart">Cart</string> <string name="content">Content goes here</string> </resources>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javarticles.android" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/Theme.Javarticles" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" /> </activity> </application> </manifest>
Run the application
Download the source code
This was an example about Android Toolbar.