Android introduces a new Toolbar widget. It is a generalization of the Action Bar pattern that gives us much more control and flexibility. ActionBar now is considered a special kind of Toolbar.
Using a Toolbar as an replacement to ActionBar:
Greater control to customize its appearance.
Fully support to lower android os devices via AppCompact support lib.
Continue to use the ActionBar features such as menus, selections, etc.
Use a standalone Toolbar, put it where ever we want in app.
Update menu layout xml in res/menu/ to have this button
Update onOptionsItemSelected() to add listener
Update menu layout xml
Button will appear directly in toolbar or in overflow menu according to:
app:showAsAction="ifRoom" - button will be displayed on toolbar if there is enough room in the toolbar; if not, it will be in overflow menu.
app:showAsAction="never" - Only in the overflow menu.
Update onOptionsItemSelected() to add Listener
Adding an Up Action
Up button in toolbar is for all activities (except the main one) to navigate to the parent activity.
Two steps:
Declare a Parent Activity
Enable the Up button for an activity
Declare a Parent Activity
In AndroidManifest.xml:
For higher than Android 4.1 (API level 16), using android:parentActivityName.
For older version, using <meta-data> name-value pair, where name is android.support.PARENT_ACTIVITY with value the name of the parent activity.
Enable Up button
Action Views
It is an action providing rich functionality. For example, a search action view allows the user to type their search text in toolbar, without having to change activities or fragments.
Add <item> in toolbar menu resource
Update onCreateOptionsMenu() to add event listener
Update toolbar menu resource
To add an action view, create an <item> element in the toolbar’s menu resource. Then add one of the following two attributes to the element:
actionViewClass - The class of a widget that implements the action.
actionLayout - A layout resource describing the action’s components.
Set showAsAction to either ifRoom|collapseActionView or never|collapseActionView.
The collapseActionView indicates how to display the widget when the user is not interacting with it: If the widget is on toolbar, the app should display the widget as an icon. If the widget is in the overflow menu, the app should display the widget as a menu item. When the user interacts with the action view, it expands to fill toolbar.
Update onCreateOptionsMenu()
Update onCreateOptionsMenu() in activity to add event listener
Listener to action view collapse/expanded
If we want to do something when action view collapses/expands:
Define and override OnActionExpandListener
Add this listener to action view item
Action Providers
It is an action with its own customized layout. When user clicks it, the action provider controls the action’s behavior in any way we want. For example, the action provider might respond to a click by displaying a menu.