我目前有一个带标题的工具栏的抽屉导航,我希望将此标题置于工具栏的中央,但工具栏似乎没有考虑抽屉图标,如下图所示。
而当我对不在抽屉导航内的其他 Activity 使用相同的工具栏布局时,标题完美居中,如下图所示:
那么我如何让它考虑到这个图标呢?
这是我的布局:
<android.support.design.widget.AppBarLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="@style/Theme.App.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/black"
app:popupTheme="@style/Theme.App.PopupOverlay">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@color/white"
android:textStyle="bold"
android:text="Title"
android:textSize="16sp" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
最佳答案
您需要了解工具栏小部件扩展了 ViewGroup类,它有自己的 LayoutParams .
因此您不需要在 Toolbar 中使用 RelativeLayout,而只需添加带有 TextView 的单行。
android:layout_gravity="center_horizontal"
最终的 xml 应该是这样的,
<android.support.design.widget.AppBarLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Theme.App.AppBarOverlay" >
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/black"
app:popupTheme="@style/Theme.App.PopupOverlay" >
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Title"
android:textColor="@color/white"
android:textSize="16sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
关于带抽屉导航的 Android 中心标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33664466/