Actually AppBarLayout has special method to apply such offset:
final int setAppBarTopBottomOffset(CoordinatorLayout coordinatorLayout, AppBarLayout appBarLayout, int newOffset, int minOffset, int maxOffset)
Unfortunately it has package-private access level, but we can invoke it through such intermediate chain:
private void setAppBarOffset(int offsetPx){
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams();
AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
behavior.onNestedPreScroll(mCoordinatorLayour, mAppBarLayout, null, 0, offsetPx, new int[]{0, 0});
}
One thing to be mentioned - this method should be called after mAppBarLayout is already prepared and measured. So the right way is to call it via view's post method.
mCoordinatorLayour = (CoordinatorLayout) findViewById(R.id.root_coordinator);
mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar_layout);
mAppBarLayout.post(new Runnable() {
@Override
public void run() {
int heightPx = findViewById(R.id.iv_header).getHeight();
setAppBarOffset(heightPx/2);
}
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…