CollapsingToolbarLayout的app:collapsedTitleGravity=center属性失效求助
嘿,我来帮你搞定这个CollapsingToolbarLayout的标题居中问题!
1. 这是Design Support库的问题吗?
其实不能完全算是BUG,这是它的设计逻辑带来的小坑。当你调用setSupportActionBar(toolbar)并启用返回按钮后,Toolbar会在左侧预留出导航按钮的空间——也就是你看到的那个“无名视图”,它其实是ActionBar的导航区域容器。而CollapsingToolbarLayout在折叠状态下计算标题居中位置时,并没有考虑这个导航按钮占据的宽度,导致标题被挤向右侧,看起来没居中。
2. 解决办法
这里给你两种实用的解决方案:
方法一:让CollapsingToolbarLayout全权管理标题(推荐)
这种方式避开ActionBar的默认布局逻辑,让标题完全由CollapsingToolbarLayout控制,能彻底解决居中问题:
步骤1:修改布局文件
调整Toolbar和CollapsingToolbarLayout的内边距属性:
<android.support.design.widget.CollapsingToolbarLayout android:id="@+id/ctl_profile" android:layout_width="match_parent" android:layout_height="match_parent" app:contentScrim="?attr/colorPrimary" android:layout_marginTop="52dp" app:expandedTitleMarginStart="16dp" app:layout_scrollFlags="scroll|exitUntilCollapsed|snap" app:collapsedTitleGravity="center_horizontal" app:collapsedTitleMarginStart="0dp"> <android.support.v7.widget.AppCompatImageView android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:src="@mipmap/ic_launcher" app:layout_collapseMode="parallax"/> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/AppTheme.PopupOverlay" app:contentInsetStart="0dp" app:contentInsetLeft="0dp"> </android.support.v7.widget.Toolbar> </android.support.design.widget.CollapsingToolbarLayout>
步骤2:修改Java代码
放弃使用setSupportActionBar,直接用CollapsingToolbarLayout设置标题,手动处理返回按钮:
// 清空Toolbar的标题,避免冲突 toolbar.setTitle(""); // 设置CollapsingToolbarLayout的标题 CollapsingToolbarLayout collapsingToolbar = findViewById(R.id.ctl_profile); collapsingToolbar.setTitle("你的标题内容"); // 手动添加返回按钮点击事件 toolbar.setNavigationOnClickListener(v -> onBackPressed());
方法二:保留ActionBar逻辑,调整内边距适配
如果你必须使用setSupportActionBar的默认逻辑,可以通过调整边距让标题居中:
步骤1:修改布局文件
给Toolbar添加contentInsetStartWithNavigation="0dp"消除导航按钮的内边距,同时给CollapsingToolbarLayout设置collapsedTitleMarginStart="48dp"(导航按钮的标准宽度是48dp,抵消它的宽度让标题居中):
<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/AppTheme.PopupOverlay" app:contentInsetStartWithNavigation="0dp"/> <android.support.design.widget.CollapsingToolbarLayout ... app:collapsedTitleMarginStart="48dp"/>
步骤2:代码保持原有设置
确保CollapsingToolbarLayout和ActionBar的标题一致即可:
setSupportActionBar(toolbar); Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("你的标题内容"); // 同步CollapsingToolbarLayout的标题 findViewById(R.id.ctl_profile).setTitle("你的标题内容");
另外补充一句:你看到的那个“可疑无名视图”就是Toolbar用来容纳返回按钮的容器,属于ActionBar的默认布局元素,并不是异常视图哦~
内容的提问来源于stack exchange,提问作者amlwin

