Android ToolBar using full parsing

Source: Internet
Author: User

Toolbar Introduction

toolbar is a new navigation control introduced by Android 5.0 to replace the previous Actionbar, due to its high degree of customization, flexibility, material design style and other advantages, more and more applications are also used toolbar, For example, the most commonly used knowledge of the software's top navigation bar is the use of toolbar. Official considering that there are still some users of mobile phone version number is less than 5.0, so, toolbar also put in the support V7 package, so that the lower version of the system can also use the toolbar. This article will be used to explain the toolbar of the support V7 supporting package, including its basic usage, style customization and other knowledge points.

Basic use of toolbar introduces support V7 supporting package

Enter the following code in the Build.gradle of your project to introduce a support package with backwards compatible toolbar:

dependencies {          ‘libs‘, include: [‘*.jar‘])          ‘com.android.support:appcompat-v7:23.1.1‘}
Change theme

In order to be able to use toolbar, we need to hide the original Actionbar, this can be modified in the theme, in Values/styles.xml to make the following changes:

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

Inheriting the Theme.Appcompat.Light.NoActionBar theme, here is a theme.appcompat that supports the theme within the package and corresponds to the 5.0 version of the theme.material theme. This topic is then referenced in the manifest file.

Create this control in the layout file, in the Activity_main.xml file, as shown in the code below:
<framelayout xmlns:android=  "http://schemas.android.com/apk/res/android"  android:layout_width=" match_parent " android:layout_height=" match_parent " > <android.support.v7.widget.toolbar android:id= "@+id/toolbar"  android:lay Out_width= "wrap_content"  android:layout_height= "wrap            _content " > <textview android:layout_width=" match_parent " Android:layout_height= "wrap_content"  android:text=" title " android:textsize=/> </android.support.v7.wi Dget. Toolbar></framelayout>  

On top, Created the Android.support.v7.widget.Toolbar, and we put a textview inside, which is the biggest difference from Actionbar, because Toolbar is actually a viewgroup that supports putting sub-view inside it. OK, we run the program and get the following result:

can see toolbar normal display, of course, this is only the simplest usage, then we gradually add content, style, so that it looks more beautiful, more perfect function.

The Perfection of toolbar one, first of all we consider, change the color of toolbar

To change the color of the toolbar is simple, add a Backgroud property to the layout file to specify the color, but for global consideration, we can: in the Values/styles.xml file, make the following changes:

<resources>    <style name="Apptheme" parent="Theme.AppCompat.Light.NoActionBar" ><! -- Customize your Theme here. --> <item name= "colorprimary" >#2e8abb</Item > <! - -light blue --> <item name= "colorprimarydark" ># 3A5FCD</Item> <! - -dark blue --></style></Resources>

Then, in the layout file, add the following properties:

android:background="?attr/colorPrimary"

In this way, it is convenient for each toolbar to refer to the same color, we first see what the effect is now:

As you can see, the color has changed and we notice that the color of the top status bar has also become dark blue, because the "Colorprimarydark" attribute is added, so that the top status bar changes, and with this feature, we can easily achieve the "status bar immersion" effect. Of course, this only applies to Android 5.0 above, if the lower version then this property is invalid. Here is attached a picture (image from http://blog.csdn.net/bbld_/article/details/41439715):

According to the instructions in the diagram, we can easily customize our style in the Styles.xml file, and if you want to change the color of the toolbar title, subtitle, and the text in the menu, you can take advantage of the Textcolorprimary property and so on.

Second, add title, subtitle, logo, navigation bar icon

The mainactivity file gets an instance of the control first, followed by a series of set methods, with the following code:

 Public  class mainactivity extends appcompatactivity {    PrivateToolbar Toolbar;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        toolbar = (toolbar) Findviewbyid (R.id.toolbar); Toolbar.settitle ("Title"); Toolbar.setsubtitle ("SubTitle"); Toolbar.setlogo (R.mipmap.ic_launcher);//Set the navigation icon after the Setsupportactionbar methodSetsupportactionbar (toolbar);    Toolbar.setnavigationicon (R.mipmap.ic_drawer_home); }}

The results are as follows:

If you want to change the font size, color, and so on for headings and subheadings, you can call settitletextcolor , settitletextappearance , setsubtitletextcolor , setsubtitletextappearance these APIs. Of course, these settings are supported directly in the XML layout, but instead of the Android: namespace, you can customize the namespace as follows:

<framelayout xmlns:android="Http://schemas.android.com/apk/res/android"  Xmlns:toolbar="Http://schemas.android.com/apk/res-auto" ... >            <android.support.v7.widget.Toolbar ... Toolbar:logo= "@mipmap/ic_launcher"toolbar:title="title"toolbar: Subtitle="Sub Title"toolbar:titletextcolor="#ffffff">                                            </android.support.v7.widget.Toolbar></framelayout>
Third, add menu option icon and click Event 1. Add menu option icon

General navigation bar, on the right side there are menu options, of course, toolbar also support the custom menu, first of all we in the menu file, modified as follows: Res/menu/menu_main.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:id="@+id/action_search"android:title="Search" Android:icon= "@mipmap/ic_search"app:showasaction="Ifroom"/>                            <item android:id="@+id/action_notifications"android:title= "Notifications" Android:icon= "@mipmap/ic_notifications"app:showasaction="Ifroom"/ >                            <item android:id="@+id/action_settings"android:title="@string/ Action_settings "android:orderincategory="android:icon= "@mipmap/ic_ Launcher "app:showasaction=" Never "/>                                </Menu>

Here is a familiar: app:showasaction= "Ifroom"/"Never", the app is a custom namespace, because our activity inherits Appcompatactivity, is the support V7 package, is not native SDK internal, therefore cannot use android:showasaction, otherwise will error. Then ifroom indicates that there is room to display, never means never display, but is displayed through Overflowwindow.
And then we're going to rewrite the Oncreateoptionsmenu () method in the activity to load this menu in:

@Overridepublicboolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.menu_main, menu);          returntrue;}
2. Add a Click event

Menu has, we want to add a click event for the menu, so that the menu will have a practical purpose, add click event is also very convenient, you can do this:

//Set navigation icon, add menu click event to After Setsupportactionbar methodSetsupportactionbar (toolbar);        Toolbar.setnavigationicon (R.mipmap.ic_drawer_home); Toolbar.setonmenuitemclicklistener (NewToolbar.onmenuitemclicklistener () {@Override             Public Boolean Onmenuitemclick(MenuItem Item) {Switch(Item.getitemid ()) { CaseR.id.action_search:toast.maketext (mainactivity. This,"Search!", Toast.length_short). Show (); Break; CaseR.id.action_notifications:toast.maketext (mainactivity. This,"Notificationa!", Toast.length_short). Show (); Break; CaseR.id.action_settings:toast.maketext (mainactivity. This,"Settings!", Toast.length_short). Show (); Break; }return true; }        });

The results are as follows:

As you can see, the menu option icon is displayed normally, and the Click event is triggered normally, but there is a slight flaw in the place, that is the top right corner of the three dots, is black, and the icon is out of tune, there is no way to change it? The answer is yes, you can change it by adding the style as follows:

<resources>    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">        ...        <item name="android:textColorSecondary">#ffffff</item>    </style></resources>

The "Android:textcolorsecondary" property corresponds to the color of the three dots in the upper right corner. Change will become the color you want.

Iv. Other style Modifications modify toolbar popup menu style

We first click on the top right corner of the three points, will pop up a popup menu, as follows:

You can see the top right corner of the popup menu is a black word on the white, then there is no way to change its background color, so that the menu is displayed on the black text? The answer is yes, we can set it this way:
First, in the Styles.xml file, create a new topic:

<!-- toolbar弹出菜单样式 --><style name="ToolbarPopupTheme" parent="@style/ThemeOverlay.AppCompat.Dark">        <item name="android:colorBackground">#000000</item></style>

You can see that the parent of this topic is directly inherited from ThemeOverlay.AppCompat.Dark, is a theme of the support package, and we internally declare the "Android:colorbackground" property, We just change this property to change the background color of the menu. Next we introduce this theme in the layout file, which is also very simple, adding additional attributes for toolbar as follows:

toolbar:popupTheme="@style/ToolbarPopupTheme"

This allows you to change the background color of the popup menu with a few lines of code, as shown below:

Modify toolbar popup Menu Popup Location

We can see that the position of the popup menu is too biased, and we can modify its position so that it is under toolbar, which may look more beautiful:
Modify the Styles.xml file as follows:

<style name="Toolbarpopuptheme" parent="@style/ ThemeOverlay.AppCompat.Dark "><item name= "android: Colorbackground">#000000</  Item> <item name= "actionoverflowmenustyle" >@style/ Overflowmenustyle</item> <!--added an item to control menu--> </style><style name= "Overflowmenustyle" parent=" Widget.AppCompat.Light.PopupMenu.Overflow "><item name= "overlapanchor" >false</Item> <! --Change this property to false to make the menu position under toolbar -->  </style>

Effects such as:

So far, for the relevant use of toolbar to tell the end, you can see toolbar flexibility is very high, can customize a lot of styles, we usually develop also encounter a variety of different styles, so toolbar to replace Actionbar is very suitable. If there are any other styles, I will share them, thank you.

Android ToolBar using full parsing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.