ViewGroup inside CollapsingToolbarLayout show extra bottom padding when set fitsSystemWindows to be true

前端 未结 7 2350
有刺的猬
有刺的猬 2021-02-08 15:05

I am building an application and there is a profile fragment which shows a profile background image and some other elements. Like the screenshot below:

My quest

7条回答
  •  -上瘾入骨i
    2021-02-08 15:57

    create a new class extend CollapsingToolbarLayout and override the onMeasure method

    public class FixCollapsingToolbarLayout extends CollapsingToolbarLayout {
    
    
        public FixCollapsingToolbarLayout(Context context) {
            super(context);
        }
    
        public FixCollapsingToolbarLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public FixCollapsingToolbarLayout(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            try {
                Field fs = this.getClass().getSuperclass().getDeclaredField("mLastInsets");
                fs.setAccessible(true);
                WindowInsetsCompat mLastInsets = (WindowInsetsCompat) fs.get(this);
                final int mode = MeasureSpec.getMode(heightMeasureSpec);
                int topInset = mLastInsets != null ? mLastInsets.getSystemWindowInsetTop() : 0;
                if (mode == MeasureSpec.UNSPECIFIED && topInset > 0) {
                    // fix the bottom empty padding
                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(
                            getMeasuredHeight() - topInset, MeasureSpec.EXACTLY);
                    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                }
            } catch (Exception e) {
                LogUtils.e(e);
            }
        }
    }
    

提交回复
热议问题