CollapsingToolbarLayout中心TextView在工具栏中

时间:2016-03-03 07:17:35

标签: android toolbar android-collapsingtoolbarlayout

我想在工具栏中使用toolbar_title布局中心,但它看起来左边有一些边距,如果我删除了CollapsingToolbarLayout就可以了。 为了使toolbar_title文本居中,我在工具代码中设置了too​​lbar_title的边距,但是只有在片段恢复之后我才能获得正确的值,所以我postDelayed 50 ms来做到这一点。

现在问题是: 如何在CoordinatorLayout中以更好的方式居中toolbar_title?

<android.support.design.widget.CoordinatorLayout
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="match_parent"
xmlns:tools="http://schemas.android.com/tools">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:expandedTitleMarginStart="?attr/actionBarSize"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <LinearLayout
            android:id="@+id/layout_header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#f5f5f5"
            android:orientation="vertical"
            app:layout_collapseMode="parallax">
        </LinearLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/AppTheme.ToolBar"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <TextView
                android:id="@+id/toolbar_title"
                style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:textColor="@android:color/white"
                android:textSize="18sp"
                tools:text="title"/>

        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

1 个答案:

答案 0 :(得分:0)

您只需在工具栏中添加以下属性即可。

app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"

在stackoverflow上查看类似的线程:Android API 21 Toolbar Padding

在工具栏中添加属性之前和之后查看标题文本视图位置。

添加属性之前:

Before adding attributes

添加属性后

enter image description here