Android Development Note (119) Toolbar toolbar

Source: Internet
Author: User

toolbar in the previous blog "Android Development note (20) Top navigation bar", we learned the use of Actionbar, but Actionbar really is not very useful, such as text style can not be customized, icons can not be customized, but also has a low version of compatibility issues, Therefore, the actual development of people still do not tend to use actionbar. For this reason, Android provides the Enhanced Toolbar control, toolbar, because toolbar inherits from ViewGroup and can be used in layout files like other layout views, so flexibility is greatly improved. Since Android is advancing with the times, then we can not lag behind, now to learn to learn the use of toolbar.


The import Android-support-v7-appcompattoolbar is included in the Android-support-v7-appcompat.jar package, but the app project is not yet able to use the jar package directly because V7-appcompat is a complete project, the jar The package contains a lot of reference to the project in the picture resources, so we have to import V7-appcompat into a library project, and then the app project again reference this library project. The specific steps are as follows:
1. The "Android support Library" in the SDK's extra component is updated to the latest version.
2, the V7-appcompat import into a library project, V7-appcompat source path is Sdk\extras\android\support\v7\appcompat.
3. Change the target in Project.Properties to 23 (notice that the library Works and app works are changed), otherwise the following error will appear:
Error:error Retrieving parent for item:no Resource found that matches the given name ' Android:TextAppearance.Material.Wid Get. Button.inverse '.
Error:error Retrieving parent for item:no Resource found that matches the given name ' Android:Widget.Material.Button.Colo Red '.
4, delete values-v11 and values-v14 under the Styles.xml (Notice Library engineering and app project are to delete), or compile error:
Java.lang.RuntimeException:Unable to start Activity componentinfo{com.example.exmtoolbar/ Com.example.exmtoolbar.MainActivity}: Java.lang.IllegalStateException:You need to use a theme.appcompat Theme (or descendant) with this activity.


Introduce toolbar in the project because toolbar and Actionbar both occupy the top navigation bar, so to introduce toolbar you have to close the Actionbar first, the steps are as follows:
1. Define a style style that does not contain actionbar in Styles.xml
    <style name= "Appbasetheme" parent= "Theme.AppCompat.Light.NoActionBar" >        <item name= "Colorprimary" > @color/blue_light</item>        <item name= "Colorprimarydark" > @color/blue_light</item>        < Item Name= "Coloraccent" > @color/blue_light</item>    </style>
2, modify the Androidmanifest.xml, the application node Android:theme attribute value changed to the style defined in the first step, such as android:theme= "@style/appbasetheme"
3. The root node of the page layout file is changed to LinearLayout and vertical vertically, and then a toolbar element is added because toolbar is essentially a viewgroup, so you can add other controls underneath it. Here is an example of a layout fragment:
    <android.support.v7.widget.toolbar        android:id= "@+id/tl_head"        android:layout_width= "Match_parent"        android:layout_height= "Wrap_content"/>
4, the activity code to inherit appcompatactivity, note that the early V7 package is not appcompatactivity, so the front said to first update the V7 package to the latest version.
5, the same modification androidmanifest.xml, to the Activity node to supplement the attribute value Android:theme= "@style/appbasetheme"
6. Return to the activity code, get a Toolbar object, and call the Setsupportactionbar method to set the default navigation bar for the current toolbar.


The common Method of toolbar toolbar is more flexible than actionbar, mainly it provides several methods to modify the control style, the following is the common method of toolbar:
Setlogo: Sets the toolbar icon.
Settitle: Sets the caption text.
Settitletextappearance: Sets the text style of the caption.
Settitletextcolor: Sets the text color of the caption.
Setsubtitle: Sets the subtitle text. Subtitle below the title.
Setsubtitletextappearance: Sets the text style of the subtitle.
Setsubtitletextcolor: Sets the text color of the subtitle.
Setnavigationicon: Sets the navigation icon. The navigation icon is on the left side of the toolbar icon.
Setnavigationonclicklistener: Sets the click Listener for the navigation icon.
Setoverflowicon: Sets the button icon for the overflow menu.
Showoverflowmenu: Displays an overflow menu icon.
Hideoverflowmenu: Hides the overflow menu icon.
Dismisspopupmenus: Closes the popup menu.


SEARCHVIEWV7 package brought toolbar, but also brought a strengthened version of the Searchview. For instructions on the use of the original Searchview, see the Android Development note (20) top navigation bar, the old and new two searchview are used in much the same ways, of course, the newer version of the function will be more powerful, Here are the main differences between Android.widget.SearchView and Android.support.v7.widget.SearchView:

The difference between the two when they are called:
1, the menu layout file, the old Searchview is android:actionviewclass= "Android.widget.SearchView", and the new Searchview is the app: Actionviewclass= "Android.support.v7.widget.SearchView"
2. Get the Searchview object in the code, and the new control can be obtained through the Getactionview method of the V7 class Menuitemcompat.
Searchview Searchview = (searchview) menuitemcompat.getactionview (MenuItem);

The difference between the two functions:
1, the edit box is actually a Searchautocomplete control, the control in the old Searchview is hidden, in the new Searchview is open, so we can modify the V7 edit box display style.
2, based on the previous point, the new control is desirable to the Searchautocomplete object, so we can register the automatic completion of the string adapter, when the user input text, the interface will automatically pop up matching the search criteria list of keywords;
3, the Setappsearchdata method is hidden in the old Searchview, is open in the new Searchview, so the old control can only pass the search text to the result page, and the new control allows to pass other additional information to the search results page.


Toolbar operation problem processing collection to change the navigation bar or there are some compatibility issues, the following is a few of the findings of Bo Master and its solutions:

1. The menu item of the overflow menu has been set to android:showasaction= "Ifroom", but even if there is room on the toolbar, the item will not appear on the toolbar. Workaround:
Add the Properties xmlns:app= "Http://schemas.android.com/apk/res-auto" to the menu root node of the menus layout file and change the android:showasaction= "Ifroom" to the app: Showasaction= "Ifroom".

2, overflow menu list in the menu text to show the icon on the left side of the method, using Actionbar Normal, when using toolbar will not show the icon. Workaround:
Actionbar's Featureid is 8,toolbar's Featureid is 108, so in the icon display method inside, to judge both values, but not as before just Judge Window.feature_action_bar. The following changes are displayed for the icon:
    Show Overflowmenu icon public static void setoverflowiconvisible (int featureid, menu menu) {//actionbar Featureid is 8, The Featureid of toolbar is 108        if (featureid%100 = = Window.feature_action_bar && Menu! = null) {            if ( Menu.getclass (). Getsimplename (). Equals ("Menubuilder")) {                try {                    Method m = Menu.getclass (). Getdeclaredmethod (                            "setoptionaliconsvisible", boolean.type);                    M.setaccessible (true);                    M.invoke (menu, True);                } catch (Exception e) {                    log.d (TAG, E.getmessage ());}}}}    

3. When the code calls the Getactionview method to get the Searchview object, the Searchview found is empty. Workaround:
Change the android:actionviewclass= "Android.support.v7.widget.SearchView" in the menu layout file to App:actionviewclass= " Android.support.v7.widget.SearchView ".


The following is the use of the new toolbar and Searchview:



The following is an example of the use code for the new toolbar and Searchview:
Import Java.util.date;import Com.example.exmtoolbar.util.utils;import Android.support.v4.view.MenuItemCompat; Import Android.support.v7.app.appcompatactivity;import Android.support.v7.widget.searchview;import Android.support.v7.widget.toolbar;import Android.util.log;import Android.view.menu;import Android.view.MenuItem; Import Android.view.view;import Android.widget.adapterview;import Android.widget.AdapterView.OnItemClickListener; Import Android.widget.arrayadapter;import Android.widget.textview;import Android.widget.toast;import Android.app.searchmanager;import Android.app.searchableinfo;import Android.content.componentname;import Android.content.context;import Android.graphics.color;import Android.os.bundle;public class MainActivity extends appcompatactivity {Private final static String TAG = "mainactivity";p rivate TextView tv_desc;private string[] Mformatarra y = {"Yyyy-mm-dd HH:mm:ss", "Yyyy-mm-dd", "yyyy year mm month DD Day HH mm" ss "," yyyy years mm DD Day "};p rivate String Mformat = mformatarray[0 ];p RivatE Date mnowtime = new Date (), @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (        Savedinstancestate); Setcontentview (r.layout.activity_main); Tv_desc = (TextView) Findviewbyid (R.ID.TV_DESC);        Toolbar Tl_head = (Toolbar) Findviewbyid (R.id.tl_head);        Tl_head.setbackgroundresource (R.color.blue_light);        Tl_head.setlogo (R.drawable.ic_launcher);        Tl_head.settitle ("title");        Tl_head.setsubtitle ("subtitle");        Tl_head.setnavigationicon (R.drawable.ic_back); Setsupportactionbar (Tl_head);} private void Initsearchview (Menu menu) {MenuItem MenuItem = Menu.finditem (R.id.menu_search);    Searchview Searchview = (searchview) menuitemcompat.getactionview (MenuItem);    if (Searchview = = null) {LOG.D (TAG, "Fail to get Searchview.");    } else {//old and new Searchview common code starts Searchview.seticonifiedbydefault (TRUE);        Searchview.setsubmitbuttonenabled (TRUE);  Searchmanager Searchmanager = (searchmanager) getsystemservice (Context.search_service);      ComponentName cn = New ComponentName (this, searchresultactvity.class);         Searchableinfo info = Searchmanager.getsearchableinfo (CN);         if (info = = null) {LOG.D (TAG, "Fail to get searchresultactvity.");    } searchview.setsearchableinfo (info); Old and new Searchview common code End sac_text = (searchview.searchautocomplete) Searchview.findviewbyid (R.id.search_src_tex        T);        Sac_text.settextcolor (Color.White); Sac_text.sethinttextcolor (Color.White); Searchview.setonquerytextlistener (new Searchview.onquerytextlistener () {@ Overridepublic boolean onquerytextsubmit (String query) {return false;}                @Overridepublic boolean onquerytextchange (String newtext) {dosearch (NewText); return true;}});        Bundle bundle = new bundle ();        Bundle.putstring ("Hi", "hello");    Searchview.setappsearchdata (bundle); }}private searchview.searchautocomplete sac_text;private string[] Hintarray = {"AB", "abc", "ABCDE", "ABHTP", "Aaeet", "a AB "};p rivate void Dosearch (String text) {if (Text.indexof ("a") = = 0) {arrayadapter<string> adapter = new Arrayadapter&lt ;        String> (This, R.layout.list_auto, Hintarray); Sac_text.setadapter (adapter); Sac_text.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?>        Parent, View view,int position, long id) {TextView tv_item = (TextView) view;sac_text.settext (Tv_item.gettext ());}    });}} @Override public boolean onmenuopened (int featureid, menu menu) {//Displays the icon to the left of the menu item utils.setoverflowiconvisible          (Featureid, menu);      Return super.onmenuopened (Featureid, menu); @Overridepublic a Boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu);// Initialize the search box Initsearchview (menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem item) {int id = item.getitemid (); if (id = = Android. R.id.home) {finish ();} else if (id = = R.id.menu_refresh) {mnowtime = new Date (); Tv_desc.setteXT ("Current Refresh Time:" +utils.getformatdatetime (Mnowtime, Mformat)); return true;} else if (id = = r.id.menu_about) {Toast.maketext (This is the demo demo of the toolbar, Toast.length_long). Show (); return true;} else if (i D = = r.id.menu_quit) {finish ();} return super.onoptionsitemselected (item);}}






Click here to view the full list of Android development notes

Android Development Note (119) Toolbar toolbar

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.