Toolbar中Android Studio文本未居中,如何解决?
解决Fragment中Toolbar标题部分偏移无法居中的问题
方案1:通过样式统一设置Toolbar标题居中
直接在样式和布局层面配置,避免代码动态修改的不确定性:
- 在
res/values/styles.xml中定义标题样式:
<style name="CenteredToolbarTitle" parent="TextAppearance.Widget.AppCompat.Toolbar.Title"> <item name="android:gravity">center</item> <item name="android:textAlignment">center</item> </style>
- 在Toolbar的布局文件中引用该样式,并清除默认内边距:
<androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:titleTextAppearance="@style/CenteredToolbarTitle" app:contentInsetLeft="0dp" app:contentInsetStart="0dp" app:contentInsetRight="0dp" app:contentInsetEnd="0dp"/>
方案2:修改代码中TextView的布局参数
如果必须通过代码动态调整,将TextView的宽度设为MATCH_PARENT,确保它占满Toolbar宽度后再让文本居中:
if (appCompatTextView != null) { val params: Toolbar.LayoutParams = Toolbar.LayoutParams( Toolbar.LayoutParams.MATCH_PARENT, Toolbar.LayoutParams.WRAP_CONTENT ) params.gravity = Gravity.CENTER appCompatTextView.gravity = Gravity.CENTER appCompatTextView.layoutParams = params }
原代码中使用WRAP_CONTENT作为宽度,TextView仅包裹文本内容,若Toolbar存在默认内边距或其他元素,可能导致视觉上的偏移;改为MATCH_PARENT后,文本会在整个Toolbar宽度范围内居中。
方案3:排查Toolbar的额外干扰元素
检查出现偏移的Fragment对应的Toolbar是否存在以下情况:
- 左侧添加了导航图标(如返回键),此时需添加
app:contentInsetStartWithNavigation="0dp"属性消除图标带来的内边距偏移; - 布局中存在其他与标题TextView同级的View,占用了Toolbar的空间,导致标题位置被挤压。
内容的提问来源于stack exchange,提问作者Mihai-Cristian Condrea
相关产品推荐
相关产品推荐

