Authorative way to override onMeasure()?

后端 未结 8 2131
眼角桃花
眼角桃花 2020-12-04 07:32

What\'s the correct way of overriding onMeasure()? I\'ve seen various approaches. For example, Professional Android Development uses MeasureSpec to calculate the di

相关标签:
8条回答
  • 2020-12-04 08:02

    here is how I solved the problem:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
            ....
    
            setMeasuredDimension( measuredWidth, measuredHeight );
    
            widthMeasureSpec = MeasureSpec.makeMeasureSpec( measuredWidth, MeasureSpec.EXACTLY );
            heightMeasureSpec = MeasureSpec.makeMeasureSpec( measuredHeight, MeasureSpec.EXACTLY);
    
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    

    }

    Moreover it was necessary for the ViewPager component

    0 讨论(0)
  • 2020-12-04 08:04

    I think it depends on the parent which you are overriding.

    For example, if you are extending a ViewGroup (like FrameLayout), when you have measured the size, you should call like below

    super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
    

    because you may want to ViewGroup to do rest work (do some stuffs on child view)

    If you are extending a View (like ImageView), you can just call this.setMeasuredDimension(width, height);, because the parent class will just do something like you have done usually.

    In a word, if you want some features your parent class offers free you should call super.onMeasure() (pass MeasureSpec.EXACTLY mode measure spec usually), otherwise call this.setMeasuredDimension(width, height); is enough.

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