Authorative way to override onMeasure()?

后端 未结 8 2136
眼角桃花
眼角桃花 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: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.

提交回复
热议问题