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 {          compile fileTree(dir: ‘libs‘, include: [‘*.jar‘]) compile ‘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:layout_width=
         "wrap_content" Android:layout _height= "wrap_content" > <textview android:layout_width=  "match_parent" Android:layout_height= "Wrap_content" Android: Text= "title" Android:textsize= "20sp"/> </ Android.support.v7.widget.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:


Result 1.png


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><StyleName= "Apptheme" parent= " Theme.AppCompat.Light.NoActionBar "> <!--Customize your Theme Here. --<item name=  "colorprimary" > #2e8abb </item > <!--light blue-to <item name= "Colorprimarydark" > #3A5FCD </< Span class= "Hljs-name" >item> <!--dark blue-to </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:


Result 2.png


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):


Style description


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:

Publicclass mainactivity extends appcompatactivity {private Toolbar Toolbar;  @Override protected void oncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); toolbar = (toolbar) Findviewbyid (R.id.toolbar); Toolbar.settitle ( "SubTitle"); Toolbar.setlogo (R.mipmap.ic_launcher); //set the navigation icon after Setsupportactionbar method Setsupportactionbar (toolbar); Toolbar.setnavigationicon (R.mipmap.ic_drawer_home); }}

The results are as follows:


Result 3.png


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:

<Framelayoutxmlns:android= "http://schemas.android.com/apk/res/android" Span class= "hljs-attr" >xmlns:toolbar= "Http://schemas.android.com/apk/res-auto" ...> <android.support.v7.widget.toolbar Span class= "hljs-attr" > ... 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:

<MenuXmlns: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 "><ItemAndroid:id="@+id/action_search"android:title="Search"android:icon="@mipmap/ic_search"app:showasaction="Ifroom"/><ItemAndroid: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="  "@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:

@Overridepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true;}
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 the navigation icon, add menu click event to Setsupportactionbar (toolbar) after Setsupportactionbar method;        Toolbar.setnavigationicon (R.mipmap.ic_drawer_home); Toolbar.setonmenuitemclicklistener (New Toolbar.onmenuitemclicklistener () {@OverridePublicBooleanonmenuitemclick (MenuItem item) { Switch (Item.getitemid ()) {case R.id.action_search:toast.maketext (MainActivity.this,  "Search!", Toast.length_short). Show (); break; case r.id.action_notifications:toast.maketext (Mainactivity. This,  "Notificationa!", Toast.length_short). Show (); break; case r.id.action_settings:toast.maketext (Mainactivity. This,  "Settings!", Toast.length_short). Show (); break;} return true;});        

The results are as follows:


Result 5.png


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:


Result 6.png


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:


Result 7.png 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:

<StyleName="Toolbarpopuptheme"Parent="@style/themeoverlay.appcompat.dark" > <ItemName="Android:colorbackground" > #000000</Item><ItemName= "Actionoverflowmenustyle" > @style/overflowmenustyle</< Span class= "Hljs-name" >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 below toolbar--></STYLE>   

Effects such as:


Result 8.png

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.



Chen Yu
Links: http://www.jianshu.com/p/ae0013a4f71a
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

Android ToolBar using full parsing

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.