我要创建一个自定义视图,该视图将是AppBarLayout的子视图。我需要这个视图在我向上滚动时部分折叠,但不是完全折叠。它将有一个最小的高度,并在小尺寸模式下固定在AppBarLayout的顶部,然后在视图向下滚动时展开回大尺寸模式。
我花了很多时间研究AppBarLayout和CoordinatorLayout的来源,到目前为止,我还没有找到一种方法来做我想做的事情。当视图向上滚动时,AppBarLayout的子级必须保持可见或完全消失。
有没有人可以建议一种方法来创建appbarlayout的子级,该子级将以这种方式运行?
谢谢你
最佳答案
食谱如下:
如果设置了android:minHeight,AppBarLayout将尊重该值,不会滚动到使组件变小的点之外。所以您的XML布局可能如下:
android:layout_width="match_parent"
android:layout_height="320dp"
android:minHeight="108dp"
android:fitsSystemWindows="true"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
接下来,您要让您的类向父类注册一个OnOffsetChangedListener。当应用程序条滚动时,组件将获取事件,以便您知道如何配置视图。
class OnOffsetChangedListener implements AppBarLayout.OnOffsetChangedListener {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
final int scrollRange = appBarLayout.getTotalScrollRange();
float offsetFactor = (float) (-verticalOffset) / (float) scrollRange;
...
这将向您展示如何找到总滚动范围,然后找到总滚动范围与当前滚动位置(即应用程序栏在其滚动中的位置)之间的比率。
您应该执行AppBarLayout所做的操作;覆盖CollapsingToolbarLayout并在其中添加侦听器:
// Add an OnOffsetChangedListener if possible
final ViewParent parent = getParent();
if (parent instanceof AppBarLayout) {
if (mOnOffsetChangedListener == null) {
mOnOffsetChangedListener = new OnOffsetChangedListener();
}
((AppBarLayout) parent).addOnOffsetChangedListener(mOnOffsetChangedListener);
}
看看source code for onAttachedToWindow它会给你一些想法。你的观点需要做很多相同的事情。
您还可以查看我的示例项目,该项目的图像随着工具栏的滚动而缩放和移动:https://github.com/klarson2/Collapsing-Image