将图像添加到工具栏的中心

问题描述:

我在我的应用程序中使用工具栏而不是 actionabar.工具栏工作正常,但问题是我希望应用程序徽标出现在工具栏的中心.如果没有显示菜单项,图像将位于中心工具栏,但如果我向工具栏添加搜索或刷新菜单项,图像也会移动.我希望工具栏始终位于中心

I am using Toolbar instead of actionabar in my appliaction.The toolbar works fine but the problem is that i want the app logo to appear in the center of the toolbar.The image will be in center if no menu items are displayed on the toolbar, but if i add search or refresh menu item to the toolbar the image also shifts.I want the toolbar to be in center always

代码

<android.support.v7.widget.Toolbar
                android:id="@+id/toolbar_home"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/pink"
                android:minHeight="56dp"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:contentInsetEnd="0dp"
                app:contentInsetStart="0dp">

                <RelativeLayout
                    android:id="@+id/rl_toolbar_main"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    >


                    <ImageView
                        android:id="@+id/tv_home_header"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerInParent="true"
                        android:src="@drawable/image"
                        android:drawablePadding="10dp"
                         />


                </RelativeLayout>

            </android.support.v7.widget.Toolbar>

使用以重心为中心的可绘制位图作为工具栏背景可帮助您创建所需的效果.例如,

Using a bitmap drawable with center gravity as Toolbar background helps you create the required effect. e.g.,

假设您要居中的图像是 centeree.png,它将被包裹在 drawable/toolbar_background.xml

Let's assume your image to be centered is centeree.png, and that will be wrapped inside drawable/toolbar_background.xml

<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@android:drawable/centeree"
    android:gravity="center" />

您可以将 toolbar_background.xml 指定为布局中工具栏的背景

You can assign toolbar_background.xml as a background to toolbar in your layout

<android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@drawable/toolbar_background">

另外,您也可以使用 9 块可绘制,两侧具有相等的可拉伸区域.


Also as an alternative, you can use a 9 patch drawable with a equal stretchable area on both sides.