ToolBar标题居中以及对刘海屏的适配

2018-10-18  本文已影响180人  Crcker

一、ToolBar 标题居中

解决方法:在RelativeLayout布局中加入一个toolbar和Textview,将TextView的style设置为和Toolbar相同的样式,然后将TextView设置为基于父组件居中即可,见下面的代码。
注意:由于Toolbar继承至ViewGroup,所以有些人直接将TextView加入到Toolbar中,如果Toolbar中有返回键或者其他按钮,那么TextView将不会居中。

  <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:gravity="center"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <TextView
            style="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            />
    </RelativeLayout>

二、刘海屏的适配

在普通手机以上代码可以完美解决,不过在有刘海的手机上,会发现刘海会正好遮挡住标题,所以需要在RelativeLayout上设置layout_marginTop以及设置fitsSystemWindows="true",代码如下

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/toolbar_bg_color"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"

            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:gravity="center"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <TextView
            style="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            />
    </RelativeLayout>

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

上一篇 下一篇

猜你喜欢

热点阅读