Based on Yevhenii's answer above, I think I managed to solve this in an even simpler way:
class KeepWithinParentBoundsScrollingBehavior : AppBarLayout.ScrollingViewBehavior {
constructor() : super()
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean {
if (dependency !is AppBarLayout) {
return super.onDependentViewChanged(parent, child, dependency)
}
val layoutParams = child.layoutParams as CoordinatorLayout.LayoutParams
layoutParams.height = parent.height - dependency.bottom
child.layoutParams = layoutParams
return super.onDependentViewChanged(parent, child, dependency)
}
}
Then set app:layout_behavior="your.package.KeepWithinParentBoundsScrollingBehavior"
on your ViewPager
or whatever view you have below the AppBar
.
Take note that this is not a generic solution for all CoordinatorLayout
s, but it seems to work when you have a view below an app bar that you don't want to let extend beyond the bottom of the parent CoordinatorLayout.
UPDATE:
You should also set app:layout_anchor="@id/app_bar"
on your ViewPager for the situation when the keyboard disappears. If you don't the ViewPager
layout will not be refreshed when the keyboard disappears and the ViewPager
will appear cut off.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…