Preface:

Because of the need to encapsulate the Toolbar, I thoroughly studied the Toolbar, which used to be simply used, but now finds that it is completely useless.

Let’s start with an illustration:

The structure of the Toolbar is simple:

1.NavigationIcon 2.Logo 3.Title 4.subTitle 5.menu. ,3,5 commonly used: 1

Friendly tips:

GetSupportActionBar () must be called after setSupportActionBar(Toolbar, Toolbar)

Let’s start with the usual ones:

1.NavigationIcon’s methods

// Set whether to add display NavigationIcon. If void is usedsetDisplayHomeAsUpEnabled(boolean showHomeAsUp); // Set NavigationIcon to Drawable or ResId voidsetNavigationIcon(@Nullable Drawable icon);
void setNavigationIcon(@drawableres int resId) // Set NavigationIcon's click listenersetNavigationOnClickListener(OnClickListener listener);
Copy the code
Specific use:
Toolbar mToolbar = (Toolbar)findViewById(R.i.Toolbar) // Set the ToolbarsetSupportActionBar(mToolbar); // Display NavigationIcon, which is the ActionBar method. The Toolbar there is no this way. GetSupportActionBar (). SetDisplayHomeAsUpEnabled (true); / / Settings icon mToolbar. SetNavigationIcon (drawable); // Set the listenersetSupportActionBar () called after mToolbar. SetNavigationOnClickListener (clickListener);Copy the code
To summarize a few pits:

1. You must first setSupportActionBar(mToolbar).

2. SetDisplayHomeAsUpEnabled (true) is the method of ActionBar.

3. SetNavigationOnClickListener () must be in setSupportActionBar () called after take effect. Because the setSupportActionBar(Toolbar) converts the Toolbar to the Acitionbar. Listening will also reset.

2.Title

A few ways:
/ / is displayed getSupportActionBar (). SetDisplayShowTitleEnabled (Boolean showTitle); // set title.getSupportActionBar ().setTitle(title); // set title.tools.setTitle (title); // Set Margin. Toolbar.setTitleMargin(); / / set the font. The Toolbar. SetTitleTextAppearance (); / / set the word color Toolbar. SetTitleTextColor (int color);Copy the code
Conclusion:

Use relatively simple. Basically see method name to know is what. There’s nothing wrong with that. Either the Toolbar directly sets title or getSupportActionBar() and title.

3 Menu Menu

This thing is a little painful to use. There are a lot of holes.

Let’s start with creating:

@override public Boolean onCreateOptionsMenu(Menu Menu) {// Write a Menu resource file. GetMenuInflater ().inflate(R.mu.menu,menu);return super.onCreateOptionsMenu(menu);
    }

<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="com.example.acctionbaractivitydemo.MainActivity">
    <item
        android:id="@+id/menu1"/ / ICONS of the android: icon ="@mipmap/ic_launcher"/ / name android: title =""
        app:showAsAction="withText|ifRoom"/>
    <item
        android:id="@+id/menu2"
        android:icon="@mipmap/ic_launcher"
        android:title="Ha ha"
        app:showAsAction="withText"/>
    <item
        android:id="@+id/menu3"
        android:icon="@mipmap/ic_launcher"
        android:title="Ha ha"
        app:showAsAction="withText"/> </menu> //showAsAction The values of this property are: //1, always: keeps the menu item displayed on the ToolBar. / / 2,ifRoom: This value causes the menu item to appear on the ToolBar if there is enough space. //3, never: makes menu items never appear on the ToolBar, in... Is displayed in the child of. WithText: Displays the menu item with its icon and menu text.Copy the code

Set Menu and click

/** * is called when a menu item is clicked, which is the menu item's listening method. */ @override public Boolean onOptionsItemSelected(MenuItem item) {returnsuper.onOptionsItemSelected(item); } // Set the toolbar to listen onsetSetting SupportActionBar(Toolbar) before may not work. Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    return false; }});Copy the code

Menu some operations

/** * called each time the menu is closed. * The menu is closed in three ways: *1. The menu button is clicked *2 again. The back button is clicked *3. The user to select a Menu item * / @ Override public void onOptionsMenuClosed (Menu Menu) {super. OnOptionsMenuClosed (Menu); } /** * called after onCreateOptionsMenu execution, before the menu is displayed; Is called before the menu is displayed, if it has already been created. Again, the * returnstrueThen the menu is displayed.falseDo not display; */ @override public Boolean onPrepareOptionsMenu(Menu Menu) {returnsuper.onPrepareOptionsMenu(menu); } /** * display menu icon, through reflection, set menu icon displayreturn
     */
    @Override
    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
        if(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.e(getClass().getSimpleName(), "onMenuOpened... unable to set icons for overflow menu", e); }}}return super.onPrepareOptionsPanel(view, menu);
    }

Copy the code

Style configuration:

The style configuration feels pretty gross. Pit very much

Basic configuration:

 <style name="toolbar">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item> // Sets the minimum height of the toolbar. The meaning of this setting is to solve the problem of fitness, standard MD height"android:minHeight">? attr/actionBarSize</item> <item name="android:background">@color/colorPrimary</item> // Set immersion, <item name="android:fitsSystemWindows">true</item>
    </style>
Copy the code

Some of the style methods must be at least Sdk21 to use, so this is the case

Create a values-v21 folder and write a style. You’ll have to do some configuration. Change the style in normal values to the following:

 <style name="toolbar">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:minHeight">? attr/actionBarSize</item> <item name="android:background">@color/colorPrimary</item>

        <item name="android:fitsSystemWindows">true</item>
    </style>
    <style name="base_toolbar" parent="toolbar"/>

Copy the code

The style in values-v21 is as follows:

 <style name="base_toolbar" parent="@style/toolbar">
        <item name="android:elevation">3dp</item>
        <item name="android:navigationIcon">? attr/homeAsUpIndicator</item> </style>Copy the code

Use this style

   style="@style/base_toolbar"
Copy the code

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — line — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Now let’s talk about the pit in style:
1. App: Theme for the —————— Toolbar
2. App :popupTheme———— The theme of the pop-up menu.
<! -- ToolBar Style.--> <style name= "ToolBar style""toolbar_theme" parent="@style/ThemeOverlay.AppCompat.Dark">
        <item name="android:textSize">18sp</item> <! </style> <! < span style = "color: RGB (0, 0, 0)"popup_theme" parent="@style/ThemeOverlay.AppCompat.Dark">
        <item name="android:background">@android:color/white</item>
        <item name="android:textColor">@android:color/holo_red_dark</item>
    </style>
Copy the code
ThemeOverlay.AppCompat is inherited:

If you are using a Dark theme, the font is white. The background of the menu is black

If you are using a Light theme, the font and icon will be black, while the menu background will be white

Here’s what went wrong:

1. Change the font for the Toolbar
<! -- ToolBar Style.--> <style name= "ToolBar style""toolbar_theme" parent="@style/ThemeOverlay.AppCompat.Light"> <! Change the Title color of the Toolbar. Correct --> <item name="android:textColorPrimary">@android:color/holo_red_dark</item> <! --> <item name= <item name="textColorPrimary">@android:color/holo_red_dark</item> <! Change the toolbar subtitle color. Correct --> <item name="subtitleTextColor">@android:color/holo_red_dark</item>
   </style>
Copy the code
2. Change the Menu fold icon and NavigationIcon colors on the Toolbar
<style name="toolbar_theme" parent="@style/ThemeOverlay.AppCompat.Light"> <! - Correct, this requires Api greater than 21--> <item name="android:colorControlNormal">@android:color/holo_red_dark</item> <! --> <item name="colorControlNormal">@android:color/holo_red_dark</item>
    </style>
Copy the code

Effect:

3. Modify the font color of menu (big pit):

Popup_theme = popup_theme = popup_theme = popup_theme

I searched for a lot of information, but found none to be correct. For example set android: actionMenuTextColor this attribute

 <style name="popup_theme" parent="@style/ThemeOverlay.AppCompat.Light"> <! --> <item name="android:actionMenuTextColor">@android:color/holo_red_dark</item>
    
    </style>
Copy the code

Later simply one attribute try good, found that in fact not so troublesome..

<! < span style = "color: RGB (0, 0, 0)"popup_theme" parent="@style/ThemeOverlay.AppCompat.Light"> <! -- Set background --> <item name="android:background">@android:color/white</item> <! -- Set font color --> <item name="android:textColor">@android:color/holo_red_dark</item>
    </style>
Copy the code

Effect:

4. Menu Displays the menu

The default looks like this:

You can modify this property of the popupTheme to set it:

<! -- Set not to overwrite anchor points --> <item name="overlapAnchor">false</item>
Copy the code

Some sources say to set it like this:

<! < span style = "color: RGB (0, 0, 0)"popup_theme" parent="@style/ThemeOverlay.AppCompat.Light">
        <item name="actionOverflowMenuStyle">@style/OverflowMenuStyle</item>
 </style>
 <style name="OverflowMenuStyle"parent="Widget.AppCompat.Light.PopupMenu.Overflow"> <! -- Set not to overwrite anchor points --> <item name="overlapAnchor">false</item>
 </style>
Copy the code

It’s not necessary. You can set the overlapAnchor property in the style of app:popupTheme. However, be sure to set it in the app:popupTheme style, not the app:theme style.

The final effect is as follows:

The style code for the final effect:

    <style name="toolbar">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:minHeight">? attr/actionBarSize</item> <item name="android:background">@color/colorPrimary</item>
        <item name="android:fitsSystemWindows">true</item>
    </style>
   <style name="base_toolbar" parent="toolbar"/></style> <! < span style = "color: RGB (0, 0, 0)"toolbar_theme" parent="@style/ThemeOverlay.AppCompat.Light"> <! -- Change the Title(Title) color of the Toolbar --> <item name="android:textColorPrimary">@android:color/holo_red_dark</item> <! Change the toolbar subtitle(subtitle) color --> <item name="subtitleTextColor">@android:color/holo_red_dark</item> <! --> <item name= change the toolbar icon color"colorControlNormal">@android:color/holo_red_dark</item> </style> <! < span style = "color: RGB (0, 0, 0)"popup_theme" parent="@style/ThemeOverlay.AppCompat.Light"> <! -- Set background --> <item name="android:background">@android:color/white</item> <! -- Set font color --> <item name="android:textColor">@android:color/holo_red_dark</item> <! -- Set not to overwrite anchor points --> <item name="overlapAnchor">false</item>
    </style>

Copy the code

Values-v21 style code:

  <style name="base_toolbar" parent="@style/toolbar">
        <item name="android:elevation">6px</item>
        <item name="android:navigationIcon">? attr/homeAsUpIndicator</item> </style>Copy the code

Code for the Toolbar layout

<android.support.v7.widget.Toolbar
    android:id="@+id/tl_costom"
    style="@style/base_toolbar"
    app:theme="@style/toolbar_theme"
    app:popupTheme="@style/popup_theme"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
</android.support.v7.widget.Toolbar>
Copy the code
That’s it for the general basic setup.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — `

The 2017-6-21 update

Fragment uses the correct posture of the Menu menu

Pit:

 @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }
Copy the code
1. This is a trick in Frgament
2. Even ifsetHasOptionsMenu(true);I’m not going to create it, I’m going to jump to a page and come back with a result.
3. But if it’s viewPager + frgament. Other FRgament will also have menu
4. Invalid style configuration!!

Correct posture:

I can’t set up the code directly. Is not configured

The following code is insetSupportActionBar()Before the call

// Set popupstyle, such as whether to overwrite stroke point, background, font color, etc. Mtool.setpopuptheme (r.style.popup_theme) must be set before inflateMenu(); // Create menu mtool. inflateMenu(r.menu. main_home_menu) with the Toolbar. // getMenu Menu = mtool.getmenu (); // The following code is to make the menu menu collapse style, expand to display the icon icon. Otherwise the icon will not display.if(menu ! = null) {if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
           try {
                    MenuBuilder menuBuilder = (MenuBuilder) menu;
                    menuBuilder.setOptionalIconsVisible(true); } catch (Exception e) { e.printStackTrace(); }}}Copy the code

Your love and advice is my biggest motivation – –