如何在显示返回图标时居中CollapsingToolbarLayout的标题
解决CollapsingToolbarLayout标题因返回按钮偏移的居中问题
嘿,这个困扰我也经历过!左上角的返回按钮占了空间后,默认的CollapsingToolbarLayout标题总会有点偏右,想要让它真正居中,给你两个实用的方案:
方案一:自定义居中标题(最稳定可靠)
直接禁用CollapsingToolbarLayout的默认标题,在Toolbar内部自己加一个居中的TextView,这样不管有没有导航按钮,标题都能稳稳居中,还能自定义样式。
具体布局代码示例:
<com.google.android.material.appbar.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" app:title="" <!-- 关闭默认标题 --> app:layout_scrollFlags="scroll|exitUntilCollapsed"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin"> <!-- 自定义居中标题 --> <TextView android:id="@+id/toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="我的居中标题" android:textColor="@color/white" android:textSize="18sp" android:textStyle="bold" <!-- 可以根据需求调整字体样式,匹配原标题风格 --> /> </androidx.appcompat.widget.Toolbar> </com.google.android.material.appbar.CollapsingToolbarLayout>
如果需要在代码里动态修改标题,直接操作这个toolbar_title TextView就行,和操作普通TextView一样简单。
方案二:调整默认标题的位置(适合不想加额外View的场景)
如果你不想额外加TextView,可以通过代码找到CollapsingToolbarLayout内部的标题View,调整它的对齐方式。不过这个方法依赖内部实现,可能在不同版本的Material组件里有变化,需要注意兼容性。
代码示例:
val collapsingToolbar = findViewById<CollapsingToolbarLayout>(R.id.collapsing_toolbar) // 等待布局完成后获取标题View collapsingToolbar.post { val titleView = collapsingToolbar.getChildAt(0) as? TextView titleView?.let { it.gravity = Gravity.CENTER // 可选:如果还是有点偏移,可以调整左右padding it.setPadding(0, it.paddingTop, 0, it.paddingBottom) } }
不过更稳妥的是计算导航按钮的宽度,给标题View设置左边padding等于按钮宽度,这样标题就能真正居中。但这个需要获取导航按钮的宽度,步骤会多一点,不如方案一省心。
总的来说,方案一是我最推荐的,适配性强,还能灵活定制标题样式。
内容的提问来源于stack exchange,提问作者Ornithopter
相关产品推荐
相关产品推荐

