Views inside a custom ViewGroup not rendering after a size change

前端 未结 2 753
独厮守ぢ
独厮守ぢ 2020-12-28 16:29

I\'m running into a problem that has me stumped and I was hoping someone could give me some pointers.

I\'m working on an application that uses a custom ViewGroup (ac

相关标签:
2条回答
  • 2020-12-28 16:50

    I run into the same problem.

    My onMeasure() was something like this:

    @Override    
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            ...
            //calculate new width and height here
            ...
            setMeasuredDimension(newMeasureSpecWidth, newMeasureSpecHeight);
        }
    

    My mistake was that I was calling super.onMeasure() on the first line of onMeasure(), so the inner children of my ViewGroup were being calculated based on a size that was about to change.

    So my fix was doing something like this:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        ...
        //calculate new width and height here
        ...
        int newMeasureSpecWidth = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY);
        int newMeasureSpecHeight = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
        super.onMeasure(newMeasureSpecWidth, newMeasureSpecHeight);
    }
    

    So I was setting the new size to my ViewGroup using the call to super.onMeasure(), and then it is also communicating the new size to its children.

    Remember: the contract when you override onMeasure() is that you have to call setMeasuredDimension() (and you can achieve this by calling the method itself or by calling super.onMeasure())

    0 讨论(0)
  • 2020-12-28 16:56

    It's not a hack, it's how it's supposed to work. onSizeChanged() is invoked as part of the layout pass, and you cannot/should not requestLayout() during a layout pass. It is correct to post a requestLayout() on the event queue to indicate that you have changed the View hierarchy during a layout pass.

    0 讨论(0)
提交回复
热议问题