Set starting height of CollapsingToolbarLayout

前端 未结 3 774
后悔当初
后悔当初 2020-11-30 00:19

I want to be able to scroll on the ImageView inside the CollapsingToolbarLayout. So how that would be possible, and How to set a starting height of that Image view?

3条回答
  •  醉梦人生
    2020-11-30 00:38

    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);
        }
    });
    

提交回复
热议问题