CollapsingToolbarLayout问题:固定Toolbar与视图,仅Header图片视差滚动
解决黄色TextView固定、蓝色ImageView视差滚动消失的问题
你现在遇到的问题是黄色TextView跟着滚动移动,根源在于它被放在了会收缩的CollapsingToolbarLayout内部的容器里,还继承了滚动属性。咱们调整一下布局结构就能完美解决:
核心思路
- 把需要固定不动的黄色TextView直接放在
AppBarLayout下,作为和CollapsingToolbarLayout同级的子View,脱离滚动收缩的影响范围。 - 仅让蓝色ImageView留在
CollapsingToolbarLayout中,配置视差滚动属性,让它随滚动逐渐消失。 - 保留Toolbar的
pin模式,确保它始终固定在顶部。
修改后的完整布局示例
<?xml version="1.0" encoding="utf-8"?> <!-- 注意:根布局必须是CoordinatorLayout,否则AppBarLayout的滚动交互无法生效 --> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 固定的Toolbar,保持pin模式不变 --> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@android:color/white" android:elevation="4dp" app:layout_collapseMode="pin" app:title="SHOPPING BAG"/> <!-- 固定的黄色TextView,直接作为AppBarLayout的子View,不受滚动影响 --> <TextView android:id="@+id/tv_tax_rebate_msg" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/bright_yellow" android:lineSpacingExtra="6sp" android:padding="15dp" android:text="@string/tax_rebate_disclaimer" android:textAlignment="center" android:textColor="@color/black" android:textSize="10sp" fontPath="fonts/Medium-Extd.otf"/> <!-- 仅承载蓝色ImageView的CollapsingToolbarLayout,负责滚动收缩 --> <android.support.design.widget.CollapsingToolbarLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:contentScrim="@color/white" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:titleEnabled="false"> <!-- 蓝色ImageView,设置视差滚动模式 --> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/blue" android:orientation="vertical" app:layout_collapseMode="parallax"/> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <!-- 你的ScrollView,必须设置behavior属性才能和AppBarLayout联动 --> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <!-- 这里放置ScrollView的内容 --> </ScrollView> </android.support.design.widget.CoordinatorLayout>
关键调整点说明
- 黄色TextView的位置调整:从原来的
RelativeLayout中移出,直接成为AppBarLayout的子View,这样它就和Toolbar同属固定区域,不会随滚动移动。 - 精简CollapsingToolbarLayout内容:现在只保留蓝色ImageView,
CollapsingToolbarLayout的scrollFlags="scroll|exitUntilCollapsed"确保它会随滚动收缩直至消失。 - ScrollView的联动配置:必须给ScrollView加上
app:layout_behavior="@string/appbar_scrolling_view_behavior",这样滚动事件才能传递给AppBarLayout触发收缩效果。 - 移除多余容器:原来的
RelativeLayout已无存在必要,直接简化布局结构。
这样调整后,Toolbar和黄色TextView会一直固定在顶部,蓝色ImageView会以视差效果随滚动逐渐消失,完全符合你的需求~
内容的提问来源于stack exchange,提问作者j2emanue
相关产品推荐
相关产品推荐

