Recently, when I was writing a emoticons project, I used the Toolbar for the header of each page at the beginning of UI writing. The reason was that I thought it would be more convenient to use the toolbar because the theme color is the same. However, after reading a big guy’s code, I found that my idea was really too… Then I went to the Internet to find a lot of excellent projects, look at the use of others, the toolbar step by step.

Progression of the ToolBar

  • Basic use of toolbars
  • Advanced use of the Toolbar
  • Toolbars in your project

Basic use of toolbars

First we need to hide the ActionBar. So it looks like this

  • Hide the ActionBar
  <style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
  </style>
Copy the code

or

 <style name="NoActionBar" parent="AppTheme">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
 </style>
Copy the code

The theme style can be changed by colorPrimary, colorPrimaryDark, colorAccent.

  • Set the ToolBar
<android.support.constraint.ConstraintLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="? attr/actionBarSize"
        android:background="@color/dodgerblue"
        app:navigationIcon="@mipmap/back"
        app:titleTextColor="@color/colorWhite"
        app:title="Zhihu">
    </android.support.v7.widget.Toolbar>
Copy the code

Some of the toolbar’s commonly used properties are described:

  • Android: Background Sets the background color
  • NavigationIcon The above image returns to the Settings of the icon
  • App :title Sets the display title
  • App :titleTextColor Sets the title color
  • App :subtitle Sets the subtitle
  • App :subtitleTextColor Sets the subtitle color
  • App: LOGO Set the logo (there is a logo before returning the icon and title)

Advanced use of the Toolbar

The guide package

There are usually two toolbars when initializing them

Toolbar(android.support.v7.widget)
Toolbar(android.widget)
Copy the code

Import V7 package here!! Otherwise, the Toolbar class might not be found.

  • Center the Toolbar title

If you want to center a TextView in the toolbar, set layout_gravity=”center”, layout_gravity=”left” and layout_gravity=”right”.

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="? attr/actionBarSize"
        android:background="@color/dodgerblue"
        app:navigationIcon="@mipmap/back"
        app:titleTextColor="@color/colorWhite"
        app:title="Zhihu">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="toolbar"
            android:textColor="@color/colorWhite"
            android:textSize="22sp"/>
</android.support.v7.widget.Toolbar>
Copy the code

Since the Toolbar is a control that inherits from a ViewGroup, that means it can have internal controls!

The setting of the menu

Setting up the menu is actually quite simple, and it is also set when you use the BottomNavigationView. The Toolbar integration with Menu requires overwriting the Activity’s Boolean onCreateOptionsMenu(Menu Menu) method, which returns a Boolean that determines whether you created the appropriate NENu file.

  public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.toolbar_menu,menu);
        return true;
    }
Copy the code

The menu file

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/app_bar_search"
        android:title="Search"
        app:actionViewClass="android.widget.SearchView"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/menu_cycling"
        android:icon="@drawable/find"
        android:title="Sweep it."
        app:showAsAction="never" />
    <item
        android:id="@+id/collection"
        android:title="My Collection"
        app:showAsAction="never" />
</menu>
Copy the code

The acceptable values for showAsAction are:

  1. Always: Makes the menu item always appear on the ToolBar.
  2. IfRoom: This value causes the menu item to appear on the ToolBar if there is enough space.
  3. Never: Causes menu items never to appear on the ToolBar, in… Is displayed in the child of.
  4. WithText: Displays the menu item with its icon and menu text

Menu is not displayed now because there is no way to associate the menu file without setting the Actionbar. so

public void setToolBar(){
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
}

  public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.toolbar_menu,menu);
        return true;
}
Copy the code

The setSupportActionbar(Toolbar) code line should not be forgotten, otherwise the Menu will not display!!

We now find that… And the search icon is black and white font is very mismatched, and click open… Here’s the thing…

Modify the menu pop-up position and style

The Toolbar has a popupTheme =”@style/ToolbarPopupTheme” property that sets the theme for the Toolbar!

  • Modify the text style of the popup box and the style of the popup background
<style name="ToolbarTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:background">#ffffff</item><! -- Set the background color of the popbox -->
        <item name="android:textColorPrimary">#000000</item><! -- Set text color -->
        <item name="android:textSize">16sp</item><! </style>Copy the code
  • Modify the location of the pop-up box
<style name="ToolbarTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:background">#ffffff</item>
    <item name="android:textColorPrimary">#000000</item>
    <item name="android:textSize">16sp</item>
    <item name="actionOverflowMenuStyle">@style/OverflowMenuTheme</item>
</style>

<style name="OverflowMenuTheme" parent="Widget.AppCompat.PopupMenu.Overflow">
    <item name="overlapAnchor">false</item>><! -- This property is set tofalse</style> </style>Copy the code

The location text color is set, but the overflow menu and search button are ugly

  • Change the color of the overflow menu

Modify the overflow menu is to modify the corresponding theme style, is at the beginning of the article theme of change, as long as in the above plus the item name = “android: textColorSecondary”… That’s it.

<! -- Base application theme. --> <style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar"> <! -- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textColorSecondary">#ffffff</item>
</style>
Copy the code

Some corresponding listening

There are two kinds of setting monitoring: 1. Setting the monitoring of ActionBar (for the development of Menu) 2. Listens for controls and navigationIcon set inside the Toolbar

  • The menu of listening

For menu listener onOptionItemSelected(MenuItem item) this method is similar to onClickListener

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_find:
            Toast.makeText(this, "Sweep it.", Toast.LENGTH_SHORT).show();
            break;
        case R.id.menu_colection:
            Toast.makeText(this, "Collection", Toast.LENGTH_SHORT).show();
            break;
        }
        return true;
    }
Copy the code
  • Returned listener

This is where most applications handle the returned logic. Google has already designed this, so they’ve made navigationIcon’s listener separate to the Toolbar

  public void setToolbarListener(){
       toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); }}); }Copy the code

Toolbars in your project

I think the beginning of a project success lies in the UI, the UI is beautiful is really important, but also consider the problem of loading the UI time (from the do-it-yourself project began to consider these issues laugh cry = =), before always makes me very troubling is the project in the head (that is, similar to those of in the position of the toolbar controls began to put the how). I started with a relative layout for each control. Then I learned the Toolbar and started placing controls in the Toolbar, but there was a problem. The Toolbar was limited and had a lot of space that was hard to locate. Because there are so many pages where the layout of the toolbar is the same, but the style of the control has changed, the tag is very useful.

The toolbar can inherit either the LinearLayout or the Toolbar directly. Here is a way to inherit Linearlayout, which I learned in the project.

public class Toolbar extends LinearLayout implements View.OnClickListener {
    TextView title;
    ImageView back;
    public ImageView right1,right2;

    public Toolbar(Context context) {
        super(context);
        initViews();
    }

    public Toolbar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initViews();

    }

    public Toolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViews();

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public Toolbar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initViews();
    }

    private void initViews() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.widget_toolbar, this, false);
        addView(view);
        title = findViewById(R.id.title);
        right1 = findViewById(R.id.right1);
        right2 = findViewById(R.id.right2);
        findViewById(R.id.back).setOnClickListener(this);
        if(((Activity) getContext()).getTitle() ! Settitle. SetText (((Activity) getContext()).getTitle())); }setRightButtonOneShow(false); // Button not visible (GONE)setRightButtonTwoShow(false); // Button not visible (GONE)} // Set title public voidsetTitle(String title) { this.title.setText(title); } // Set whether the share button displays private voidsetRightButtonOneShow(boolean visibility){
       int i = visibility? View.VISIBLE:View.GONE;
       right1.setVisibility(i);
    }
    private void setRightButtonTwoShow(boolean visibility){
       int i = visibility? View.VISIBLE:View.GONE;
       right2.setVisibility(i);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                ((Activity) getContext()).finish();
                break; }}}Copy the code

InitViews () initializes the controls in the layout. If you don’t want to show them, you can hide them. If you are interested, you can look at the tags to hide certain controls.

Here is the.xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@color/colorPrimary"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/back"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="? attr/selectableItemBackground"
        android:padding="15dp"
        android:src="@drawable/back" />

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:lines="1"
        android:text="Title"
        android:textColor="@color/colorBlack"
        android:textSize="20sp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/right1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="? attr/selectableItemBackground"
        android:padding="15dp"
        android:src="@drawable/share" />

    <ImageView
        android:id="@+id/right2"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="? attr/selectableItemBackground"
        android:padding="15dp"
        android:src="@drawable/share" />
</LinearLayout>
Copy the code

Refer to the article

Come on!!