Material design出来有些时日,近日项目改版想尝试下新控件。使用ToolBar过程中发现标题无法居中,于是在toolBar标签中引入一个布局显示标题。
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="全部门店"
android:textColor="@color/white"
android:textSize="18sp"/>
</LinearLayout>
</android.support.v7.widget.Toolbar>
现在看起来可以居中了,有发现了新的问题。如下图,明显发现toobar有左边距
两种方法解决:
- 直接在toolBar中添加设置
app:contentInsetStart="0dp"
- 复写tooBar的style,在AppTheme中引用。这种方法一劳永逸,无需对每个toolBar设置
<style name="CustomToolBar" parent="Widget.AppCompat.Toolbar">
<item name="contentInsetStart">0dp</item>
</style>
在AppTheme中引用
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimaryDark</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorPrimaryDark</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="toolbarStyle">@style/CustomToolBar</item>
</style>
酱紫就去除了toolBar的左边距,并且居中标题啦