Replacement for the linearLayout weights mechanism

前端 未结 4 1944
渐次进展
渐次进展 2021-02-02 13:15

Background:

  • Google suggests to avoid using nested weighted linearLayouts because of performance.
  • using nested weighted linearLayout is awful to read, writ
4条回答
  •  后悔当初
    2021-02-02 13:42

    After trying your code, I just find the reason of the problems you mentioned, and it is because in your customed layout, you only layout the child properly, however you forgot to measure your child properly, which will directly affect the drawing hierarchy, so simply add the below code, and it works for me.

        @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec)-this.getPaddingRight()-this.getPaddingRight();
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    
        int heightSize = MeasureSpec.getSize(heightMeasureSpec)-this.getPaddingTop()-this.getPaddingBottom();
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    
        if(heightMode == MeasureSpec.UNSPECIFIED || widthMode == MeasureSpec.UNSPECIFIED)
            throw new IllegalArgumentException("the layout must have a exact size");
    
        for (int i = 0; i < this.getChildCount(); ++i) {
            View child = this.getChildAt(i);
            LayoutParams lp = (LayoutParams)child.getLayoutParams();
            int width = lp._viewHorizontalWeight * widthSize/(lp._leftHorizontalWeight+lp._rightHorizontalWeight+lp._viewHorizontalWeight);
            int height =  lp._viewVerticalWeight * heightSize/(lp._topVerticalWeight+lp._bottomVerticalWeight+lp._viewVerticalWeight);
            child.measure(width | MeasureSpec.EXACTLY,  height | MeasureSpec.EXACTLY);
        }
    
        this.setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
    
    }
    

提交回复
热议问题