Android Material Design toolbar and palette practice

Source: Internet
Author: User

Reprint please specify the Source: http://blog.csdn.net/bbld_/article/details/41439715 "Rocko ' s Bog"




Objective

We all know that marterial design is a new UI specification that Google has introduced, and if you don't know about it: Material Design's unofficial Chinese instruction manual, or my previous Material design translations, Compared to the previous Google in the Android Holo style of the performance of a different, Material design is now more attention by Google. With the launch of the new design language, Android's own applications are quickly using material design, such as the Play Store, Google map,google+, newer inbox, etc., and the visual experience on the Web is material, The most helpful part of this is the official introduction of material design (own ladder), and the Google app for iOS is slowly advancing. So as an Android developer how can not follow the pace of Google, following the toolbar and palette these two in the API21 after the launch of things , of course, Google has put them in the V7 library, Designing apps using material design is certainly not limited to these two aspects, and the translation of the material design in front of it is clear how to do it all. In addition to toolbar and palette This article will also describe the use of drawer under toolbar.



Toolbar

What is toolbar? Let's talk about its official introduction. toolbar is the application of the content of the Standard toolbar, can be said to be an upgrade version of Actionbar, the two are not independent relationship, to use toolbar or to be related to Actionbar. The most obvious point in comparison to Actionbar toolbar is that it becomes free to place anywhere, because it is defined as a viewgroup, so the use of actionbar is somewhat outdated, and some of its methods have been annotated obsolete.

Then how to use it, first we have to use the same V7 support package, and then define the program theme style, in style must first remove the Actionbar, a bit like to want to practice, will be first from the palace feeling AH. As follows:

/res/values/styles.xml

<resources xmlns:android= "Http://schemas.android.com/apk/res/android" > <style name= "Appbasetheme" parent= "Theme.AppCompat.Light.NoActionBar" > <!--toolbar (actionbar) Color--<item name= "Colorprimary" > #4876FF </item> <!--status bar color-<item name= "Colorprimarydark" > #3A5FCD </item> &L t;! --Window background color--<item name= "Android:windowbackground" > @android:color/white</item> <!--Sear Chview--<item name= "Searchviewstyle" > @style/mysearchviewstyle</item> </style> <sty Le name= "apptheme" parent= "@style/appbasetheme" ></style> <style name= "Mysearchviewstyle" parent= " Widget.AppCompat.SearchView "> <!--Background for the search query section (e.g. EditText) <item Nam E= "Querybackground" >...</item> Background for the Actions section (e.g. voice, submit) <item name= "Submi    Tbackground ">...</item>Close button icon <item name= "Closeicon" >...</item> Search button icon <item name= "Searchicon" > ...</item> go/commit button icon <item name= "Goicon" >...</item> Voice Search button icon &lt ; Item Name= "Voiceicon" >...</item> Commit icon shown in the query suggestion row <item name= "Commiticon" &        gt;...</item> Layout for query suggestion rows <item name= "Suggestionrowlayout" >...</item> -</style></resources>
The simplest way to remove Actionbar is to inherit the Noactionbar theme directly. The color of the property description, or the following chart is the most clear:



In addition, Searchview provides more customizable and more styles to set up in AppCompat, but generally we use the default.

And we can set the default color for the bottom navigation bar in VALUES-V21 to API21 's system version:

/res/values-v21/styles.xml

<resources xmlns:android= "Http://schemas.android.com/apk/res/android" >    <style name= "Apptheme" Parent = "@style/appbasetheme" >        <!--bottom navigation bar color--        <item name= "Android:navigationbarcolor" > #4876FF </item>    </style></resources>
Set up the next step of the theme:
Define a toolbar in the layout of the XML:

/layout/toolbar.xml

<?xml version= "1.0" encoding= "Utf-8"? ><android.support.v7.widget.toolbar xmlns:android= "/http Schemas.android.com/apk/res/android "    xmlns:app=" Http://schemas.android.com/apk/res/com.example.toolbar "    android:id= "@+id/toolbar"    android:layout_width= "match_parent"    android:layout_height= "wrap_content "    android:background="? attr/colorprimary "    android:minheight="? attr/actionbarsize "    app:popuptheme=" @style/themeoverlay.appcompat.light "    app:theme=" @style/themeoverlay.appcompat.actionbar "></ Android.support.v7.widget.toolbar>
We use toolbar as a standalone layout XML, which makes it easy to include in other layouts. You can see that we can set the properties of the toolbar here, the first above the outside also has the following properties, are the name of the understanding is not explained.




And then in the activity layout to include it in the line, of course, usually put it on the top, there is a need you can put it in the middle, the bottom or other position, it is visible that the degree of freedom is very high. The next step is the code, in OnCreate:

mtoolbar = (Toolbar) Findviewbyid (R.id.toolbar);//Toolbar.setlogo (r.drawable.ic_ launcher); Mtoolbar.settitle ("Rocko");//The text of the title must precede the Setsupportactionbar, otherwise it will be invalid//Toolbar.setsubtitle ("subtitle"); Setsupportactionbar (Mtoolbar);/* These are set by Actionbar, and note the Setsupportactionbar (toolbar); After that, the error will be */// Getsupportactionbar (). Settitle ("title");//Getsupportactionbar (). Setsubtitle ("subtitle");//Getsupportactionbar (). Setlogo (R.drawable.ic_launcher);/* The Listener of the menu can be set in toolbar or, as in Actionbar, by the activity's onoptionsitemselected callback method */ Mtoolbar.setonmenuitemclicklistener (New Toolbar.onmenuitemclicklistener () {@Overridepublic Boolean Onmenuitemclick (MenuItem Item) {switch (Item.getitemid ()) {case R.id.action_settings:toast.maketext (mainactivity.this, "Action_settings", 0). Show ( ); Break;case R.id.action_share:toast.maketext (Mainactivity.this, "Action_share", 0). Show (); break;default:break;} return true;}); 
The key point above is Setsupportactionbar (Mtoolbar), set toolbar as Actionbar. The menu can still be used and handled like Actionbar:

Res/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/ab_search "        android:orderincategory="        android: Title= "Action_search"        app:actionviewclass= "Android.support.v7.widget.SearchView"        app:showasaction= " Ifroom "/>    <item        android:id=" @+id/action_share "        android:orderincategory=" "        android: Title= "Action_share"        app:actionproviderclass= "Android.support.v7.widget.ShareActionProvider"        app: showasaction= "Ifroom"/>    <item        android:id= "@+id/action_settings" android:orderincategory= "        "        android:title=" action_settings "        app:showasaction=" Never "/></menu>
What the program looks like at this stage:
PS. Genymotion can use the 5.0 simulator.

Can you feel that this is not the same as Actionbar? Eh, the menu icon on the left is how to come out, in fact, the above has not been processed, he is navigation drawer, using the new version of V4, V7 Library Drawer The obvious point is that it has a cool interactive animation (see the last GIF). Then how to use the toolbar after the use of drawer in the toolbar. The following is of course followed by code.

/layout/activity_main.xml

<linearlayout 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:orien    tation= "vertical" tools:context= "com.example.toolbar.MainActivity" > <include layout= "@layout/toolbar"/>        <android.support.v4.widget.drawerlayout android:id= "@+id/drawer" android:layout_width= "Match_parent" android:layout_height= "Match_parent" > <!--Content interface--<linearlayout android:layou            T_width= "Match_parent" android:layout_height= "match_parent" android:orientation= "vertical" > <com.example.toolbar.widget.pagerslidingtabstrip android:id= "@+id/tabs" Android:la Yout_width= "Match_parent" android:layout_height= "48dip" > </com.example.toolbar.widget.pag Erslidingtabstrip> <android.suPport.v4.view.ViewPager android:id= "@+id/pager" android:layout_width= "Match_parent" android:layout_height= "Match_parent" > </android.support.v4.view.ViewPager> </linearl ayout> <!--Slide Menu Contents--<linearlayout android:id= "@+id/drawer_view" Android            : layout_width= "match_parent" android:layout_height= "match_parent" android:layout_gravity= "Start" android:background= "@drawable/drawer" android:orientation= "vertical" android:padding= "8DP" &            Gt        <textview android:layout_width= "match_parent" android:layout_height= "Match_parent"/> </LinearLayout> </android.support.v4.widget.DrawerLayout></LinearLayout>
Pager things can be ignored first, it will be said later. The contents of the side-slip menu are shown directly with the image for simplicity. You can see that the layout settings are similar, with different points in the code:

Getsupportactionbar (). Setdisplayhomeasupenabled (true); mdrawerlayout = (drawerlayout) Findviewbyid (R.id.drawer); Mdrawertoggle = new Actionbardrawertoggle (this, mdrawerlayout, Mtoolbar, R.string.drawer_open,r.string.drawer_close) ; Mdrawertoggle.syncstate (); Mdrawerlayout.setdrawerlistener (Mdrawertoggle);
First set the icon to display, and then the Actionbardrawertoggle as a drawerlayout listener set in, or relatively simple, the effect:

What if we need to cover the drawer toolbar? Need to slightly adjust the layout of the interface on the line, the effect is not affixed to the (brain repair, or change the source of the Setcontentview run):

<android.support.v4.widget.drawerlayout xmlns:android= "Http://schemas.android.com/apk/res/android" xmlns: tools= "Http://schemas.android.com/tools" android:id= "@+id/drawer" android:layout_width= "Match_parent" Android:lay out_height= "Match_parent" android:fitssystemwindows= "true" > <linearlayout android:layout_width= "Match_ Parent "android:layout_height=" match_parent "android:orientation=" vertical "tools:context=" Com.exampl E.toolbar.mainactivity "> <include layout=" @layout/toolbar "/> <!--Content interface--<linea Rlayout android:layout_width= "match_parent" android:layout_height= "Match_parent" Android: background= "@drawable/content" android:orientation= "vertical" > &LT;COM.EXAMPLE.TOOLBAR.WIDGET.PA                Gerslidingtabstrip android:id= "@+id/tabs" android:layout_width= "Match_parent"     android:layout_height= "48dip"           android:visibility= "Invisible" > </com.example.toolbar.widget.PagerSlidingTabStrip> <android.support.v4.view.viewpager android:id= "@+id/pager" android:layout_width= "MATC            H_parent "android:layout_height=" match_parent "android:visibility=" invisible "> </android.support.v4.view.ViewPager> </LinearLayout> </LinearLayout> <!--slide menu content--&gt    ; <linearlayout android:id= "@+id/drawer_view" android:layout_width= "Match_parent" Android:layout_hei ght= "Match_parent" android:layout_gravity= "Start" android:background= "@drawable/drawer" Android:orien tation= "Vertical" android:clickable= "true" android:padding= "8DP" > <textview Android : layout_width= "match_parent" android:layout_height= "match_parent"/> </linearlayout></android.su Pport.v4.widget.DraWerlayout> 
When you are done here, you can still click the toggle button when you pull out the menu, and set the slide-slip layout to clickable= "true" when you resolve the method. The problem with unwanted overlay toolbar on the side-by-side menu seems to be from the example provided by Google. I think since it makes the animation of this toggle button, it doesn't make sense if it's covered? Or are there other considerations? For the moment we look at Google Play, the new version of the play is not covered up.




Palette

Say palette before the first mentioned pager. Viewpager is what we should all know, General Viewpager, Xxxtabstrip, fragment three good base friends are together appear. The Xxxtabstrip here is using the Pagerslidingtabstrip on GitHub. When our pager switch with the change of fragment, and fragment content is generally different, so the general visual effect of each fragment is also different, so we can use palette to extract the main tones in fragment, That fragment what to take to Palatte to extract color, this need oneself according to own situation to decide. For example, I this demo, fragment on a TextView and to fragment set a background, then I can take the background of the picture to palette to extract color.

Said the above paragraph you also basically know palatte is used to dry, it is used to extract the color from the bitmap, and then set the color to the title AH content ah and so on.

First paste the pager part of the code:

private void Initviews () {Mtoolbar = (Toolbar) Findviewbyid (R.id.toolbar);//Toolbar.setlogo (R.drawable.ic_launcher); Mtoolbar.settitle ("Rocko");//The text of the title must precede the Setsupportactionbar, otherwise it will be invalid//Toolbar.setsubtitle ("subtitle"); Setsupportactionbar (Mtoolbar);/* These are set by Actionbar, and note the Setsupportactionbar (toolbar); After that, the error will be */// Getsupportactionbar (). Settitle ("title");//Getsupportactionbar (). Setsubtitle ("subtitle");//Getsupportactionbar (). Setlogo (R.drawable.ic_launcher);/* The Listener of the menu can be set in toolbar or, as in Actionbar, by the following two callback methods */ Mtoolbar.setonmenuitemclicklistener (New Toolbar.onmenuitemclicklistener () {@Overridepublic Boolean Onmenuitemclick (MenuItem Item) {switch (Item.getitemid ()) {case R.id.action_settings:toast.maketext (mainactivity.this, "Action_settings", 0). Show ( ); Break;case R.id.action_share:toast.maketext (Mainactivity.this, "Action_share", 0). Show (); break;default:break;} return true;}}); Getsupportactionbar (). Setdisplayhomeasupenabled (TRUE);/* Findview */mdrawerlayout = (drawerlayout) findViewById ( R.id.draWER); mdrawertoggle = new Actionbardrawertoggle (this, mdrawerlayout, Mtoolbar, R.string.drawer_open,r.string.drawer_ Close); Mdrawertoggle.syncstate (); Mdrawerlayout.setdrawerlistener (mdrawertoggle); Mpagerslidingtabstrip = ( Pagerslidingtabstrip) Findviewbyid (r.id.tabs); Mviewpager = (Viewpager) Findviewbyid (R.id.pager); Mviewpager.setadapter (New Mypageradapter (Getsupportfragmentmanager ())); Mpagerslidingtabstrip.setviewpager ( Mviewpager); Mpagerslidingtabstrip.setonpagechangelistener (new Onpagechangelistener () {@Overridepublic void onpageselected (int arg0) {colorchange (arg0);} @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {} @Overridepublic void onpagescrollstatechanged (int a rg0) {}}); Inittabsvalue ();} /** * Mpagerslidingtabstrip Default value configuration * */private void Inittabsvalue () {//Bottom cursor color mpagerslidingtabstrip.setindicatorcolor ( Color.Blue);//tab Split Line Color Mpagerslidingtabstrip.setdividercolor (color.transparent);// tab Background Mpagerslidingtabstrip.setbackgroundcolor (Color.parsecolor ("#4876FF"));// tab Bottom height mpagerslidingtabstrip.setunderlineheight ((int) typedvalue.applydimension (typedvalue.complex_unit_dip,1, Getresources (). Getdisplaymetrics ());//Cursor height mpagerslidingtabstrip.setindicatorheight ((int) Typedvalue.applydimension (typedvalue.complex_unit_dip,5, Getresources (). Getdisplaymetrics ()));// Selected text color Mpagerslidingtabstrip.setselectedtextcolor (color.white);//Normal text color Mpagerslidingtabstrip.settextcolor ( Color.Black);}

These are some basic settings, and then palette where to start working, that is, when the tab is switched. In the Onpagerselect method, 45 lines of the above code. That's what he did:

/** * Interface Color change */@SuppressLint ("Newapi") private void Colorchange (int position) {////For extracting color bitmapbitmap bitmap = bitmapfact Ory.decoderesource (Getresources (), superawesomecardfragment.getbackgroundbitmapposition (position));// Palette part Palette.generateasync (bitmap, new Palette.paletteasynclistener () {/** * callback method after extraction */@Overridepublic void ongenerated (Palette Palette) {Palette.swatch vibrant = Palette.getvibrantswatch ();/* Interface Color UI uniformity processing, looks more material */ Mpagerslidingtabstrip.setbackgroundcolor (Vibrant.getrgb ()); Mpagerslidingtabstrip.settextcolor ( Vibrant.gettitletextcolor ());//The color of the status bar, cursor, bottom navigation bar needs to be deepened or not added, The specifics are explained Mpagerslidingtabstrip.setindicatorcolor (Colorburn (Vibrant.getrgb ())) after the code; Mtoolbar.setbackgroundcolor ( Vibrant.getrgb ()); if (Android.os.Build.VERSION.SDK_INT >=) {window window = GetWindow ();//Obviously, these two goods are the new API. Window.setstatusbarcolor (Colorburn (Vibrant.getrgb ())) Window.setnavigationbarcolor (ColorBurn ()) );}}});} /** * Color Burn processing * * @param rgbvalues * RGB values, made up of alpha (transparency), red (red), green (green), Blue (blue), * We generally use its 16 binary in Android, * For example: "#FFAABBCC", the leftmost to the right, every two letters represent ALPH A (transparency), * red (red), green (green), Blue (blue). Each color value takes up one byte (8 bits), the range 0~255 * So using the shift method below to get the value of each color, and then reduce the value of each color, in the composition of the RGB color, the color will look darker * @return */private int Colorbu RN (int rgbvalues) {int alpha = Rgbvalues >> 24;int red = rgbvalues >> + & 0xff;int green = rgbvalues >  > 8 & 0xff;int blue = rgbvalues & 0xff;red = (int) Math.floor (red * (1-0.1)); green = (int) Math.floor (green * (1-0.1)); blue = (int) Math.floor (blue * (1-0.1)); return Color.rgb (red, green, blue);}
Palette need to write your own things are still relatively small, you just have to extract the completed callback method to get a variety of extracted color settings to the corresponding view on the line. The color of the picture is more vivid and prominent, convenient and intuitive to understand. The color of the extraction is very good collocation, if you have a UI designer, it is best, like my words to see it pleasing to the eye of the line. The above color processing: Like if you have toolbar as a actionbar to use and there are some obvious actionbar that visual sense Actionbutton, I think the color of the status bar should be a little darker than the toolbar color, and it looks like a bit of a dividing line. RGB color enhanced Dodge processing in Android: You can see that the way I used to deepen the color is to first get RGBColor of RedGreenBlueValue, and then decrease the value of each color, Floorfunction is the function of the downward rounding, if you can not understand the first look at the composition of the RGB color and then see it will be very well understood. When set to the same situation more is not actionbutton these obvious things or not three points of more actionbutton, looks more planar, more seamless.

Having said so much, palette is a weapon that allows us to handle the tone of the UI interface so that he is an integral part of material design.




END
Demo Effect:


Demo Source: http://download.csdn.net/detail/bbld_/8191251



Android Material Design toolbar and palette practice

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.