使用CollapsingToolbar时如何在滚动折叠过程中更新Toolbar内容
CollapsingToolbar滚动文本迁移实现方案
1. 自定义Toolbar增加附加文本区域
不需要修改Toolbar原生逻辑,直接在Toolbar内部嵌套自定义布局,预留右侧附加文本位置即可:
<!-- 自定义Toolbar布局 --> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="center_vertical"> <TextView android:id="@+id/tv_main_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold"/> <!-- 右侧附加文本区域,默认隐藏 --> <TextView android:id="@+id/tv_extra_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:textSize="14sp" android:visibility="gone"/> </LinearLayout> </androidx.appcompat.widget.Toolbar>
2. 监听折叠进度触发文本迁移
不用自行计算View可见度,直接通过AppBarLayout.OnOffsetChangedListener监听折叠状态,在到达阈值时更新Toolbar文本即可,Java实现逻辑完全一致,仅语法存在差异:
// 先声明需要的变量 private var totalScrollRange = 0 // 触发文本迁移的阈值比例,0为完全展开、1为完全折叠,可根据实际布局调整 private val triggerThreshold = 0.8f // 下方待迁移内容的目标TextView private lateinit var targetBottomTv: TextView // Toolbar内的附加文本控件 private lateinit var toolbarExtraTv: TextView
// 给AppBarLayout设置偏移监听 appBarLayout.addOnOffsetChangedListener { appBar, verticalOffset -> // 首次加载时获取总滑动范围 if (totalScrollRange == 0) { totalScrollRange = appBar.totalScrollRange } // 计算当前折叠比例 val collapsePercent = Math.abs(verticalOffset).toFloat() / totalScrollRange.toFloat() if (collapsePercent >= triggerThreshold) { // 超过阈值,同步下方文本到Toolbar并显示 if (toolbarExtraTv.text != targetBottomTv.text) { toolbarExtraTv.text = targetBottomTv.text toolbarExtraTv.visibility = View.VISIBLE // 可选:增加淡入动画让切换更自然 toolbarExtraTv.alpha = 0f toolbarExtraTv.animate().alpha(1f).setDuration(200).start() } } else { // 低于阈值,隐藏Toolbar附加文本 if (toolbarExtraTv.visibility == View.VISIBLE) { toolbarExtraTv.animate().alpha(0f).setDuration(200).withEndAction { toolbarExtraTv.visibility = View.GONE toolbarExtraTv.text = "" }.start() } } }
如果需要完全精准匹配下方View刚好消失的触发时机,可通过全局布局监听获取目标View的位置做判定:
targetBottomTv.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { // 获取下方View底部相对于父布局的位置 val targetBottomPosition = targetBottomTv.bottom // 后续偏移判断逻辑:当AppBar偏移量绝对值 >= targetBottomPosition - Toolbar高度时触发 targetBottomTv.viewTreeObserver.removeOnGlobalLayoutListener(this) } })
注意事项
- 若附加文本和主标题出现重叠,可给附加文本增加
maxWidth、ellipsize属性,或调整两个文本控件的布局权重 - 增加文本赋值、显隐状态的判断条件,避免频繁触发UI更新导致性能损耗
内容的提问来源于stack exchange,提问作者StuartDTO
相关产品推荐
相关产品推荐

