I tried setExpandTitleTextAppearance
, but it didn't work. I want to center the expanded title text.
How to center the title of a CollapsingToolbarLayout?
23.7k views Asked by Javed Khatri At
7
There are 7 answers
1
On
As Nguyễn Hoàng Anh said above, set app:titleEnabled
to false worked like a charm.
With that option enabled, after some digging with the layout inspector, suspicious unnamed-view is always added in front of TextView
inside of Toolbar
, just after 'Up' button(if it is enabled).
So even though layout gravity is working correctly, some suspicious view takes over all extra spaces inside of the Toolbar
.
1
On
In case you are trying to centre the title in the collapsed state you can use
android:paddingEnd="70dp"
android:paddingRight="70dp"
like this:
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingEnd="70dp"
android:paddingRight="70dp"
app:collapsedTitleGravity="center_horizontal"
app:expandedTitleGravity="start"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
@Javed, correct me if I wrong, you want to have the title centered in the Toolbar, then CollapsingToolbarLayout is collapsed and your layout is something like this, right?
Then you can do this trick ( i do it in onCreate of the Activity):
The key is that TextView within Toolbar has width property "Wrap Content", so we need to change it to "Match Parent". (See more about this reflection here)
Tested on Android 5.1.1 and Android 4.3 (should work pretty much everywhere)