使用CoordinatorLayout + AppBarLayout + CollapsingToolbarLayout可以实现折叠效果
CollapsingToolbarLayout + Toolbar组合使用可以实现header固定在页面顶部,但是有时候希望给CollapsingToolbarLayout设置一个最小高度,使页面最大只能滚动到指定的一个点,但是此时给CollapsingToolbarLayout设置minHeight不生效。分析CollapsingToolbarLayout源码找到了原因,记录一下。
先放自己看源码得到的结论:
- 存在Toolbar作为CollapsingToolbarLayout的直接子元素, 那么不管自己有没有单独设置minHeight,Toolbar的高度将作为CollapsingToolbarLayout的minHeight.
- 存在Toolbar, 但是不是直接子元素, maybe孙子节点. 如果CollapsingToolbarLayout设置了toolbarId属性, 则包含了引用的Toolbar元素,且是CollapsingToolbarLayout的直接子元素的视图高度将会作为CollapsingToolbarLayout的minHeight. 如果没有设置toolbarId, 视图将会一起滑动
CollapsingToolbarLayout代码分析:
ensureToolbar方法:
private void ensureToolbar() {
...
// 1
if (toolbarId != -1) {
// If we have an ID set, try and find it and it's direct parent to us
this.toolbar = findViewById(toolbarId);
if (this.toolbar != null) {
toolbarDirectChild = findDirectChild(this.toolbar);
}
}
// 2
if (this.toolbar == null) {
// If we don't have an ID, or couldn't find a Toolbar with the correct ID, try and find
// one from our direct children
Toolbar toolbar = null;
for (int i = 0, count = getChildCount(); i < count; i++) {
final View child = getChildAt(i);
if (child instanceof Toolbar) {
toolbar = (Toolbar) child;
break;
}
}
this.toolbar = toolbar;
}
...
}
代码块1: 源码也添加了注释
If we have an ID set, try and find it and it’s direct parent to us
如果CollapsingToolbarLayout有设置toolbarId属性的话,则会查找toolbar以及包含此Toolbar且是CollapsingToolbarLayout直接子元素的视图。
代码块2:如果没有设置toolbarId, 或者指定toolbarId不存在,则会去遍历CollapsingToolbarLayout的子元素查找Toolbar,注意是直接子元素. 这种情况下toolbarDirectChild总是null的
再看onLayout方法:
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
...
// Set our minimum height to enable proper AppBarLayout collapsing
if (toolbar != null) {
if (collapsingTitleEnabled && TextUtils.isEmpty(collapsingTextHelper.getText())) {
// If we do not currently have a title, try and grab it from the Toolbar
setTitle(toolbar.getTitle());
}
if (toolbarDirectChild == null || toolbarDirectChild == this) {
setMinimumHeight(getHeightWithMargins(toolbar));
} else {
setMinimumHeight(getHeightWithMargins(toolbarDirectChild));
}
}
...
}
如果Toolbar不为空的话,给CollapsingToolbarLayout设置minHeight。所以只要在ensureToolbar方法里找到了Toolbar子元素,就会给CollapsingToolbarLayout设置一个最小高度,滑出屏幕的时候始终都会有最小高度显示在屏幕上.
上面所说的minHeight是不能被覆盖的,因为即使在代码中手动设置CollapsingToolbarLayout的minHeight时会调用requestLayout, 还是会触发onLayout方法,Toolbar的高度最终会覆盖手动设置minHeight