Custom layout in Toolbar with TabLayout below

2019-05-08 04:38发布

问题:

Right now, I have a normal looking Toolbar. What I want to do is add a custom layout between the Toolbar and the TabLayout, as shown in the picture below:

On the left is what my Toolbar looks like now, and on the right is what I want it to look like.

As you can see, I want to add an ImageView and two TextViews to the layout.

How can I achieve this?

Here is my current layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tablayout"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            app:layout_scrollFlags="scroll|enterAlways" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

回答1:

AppBarLayout extends LinearLayout, so you can add any number of views to your AppBarLayout: there's no reason to add the views specifically to your Toolbar.

You'll want to make sure you use the same layout_scrollFlags as your Toolbar if you want them to scroll the same.



回答2:

Toolbar is just a ViewGroup, you can customize is as much as you want.

Try this :

<android.support.v7.widget.Toolbar
 style="@style/ToolBarStyle"
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="?attr/colorPrimary"
 android:minHeight="@dimen/abc_action_bar_default_height_material">

<ImageView
    android:layout_width="wrap_content"
    android:contentDescription="@string/logo"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:src="@drawable/ic_launcher"/>

This should bring your imageView in center of toolbar.