Search code examples
androidtextviewonmeasure

How to modify a custom TextView WRAP_CONTENT height without copying and pasting its parent onMeasure implementation?


I am creating a custom TextView and I would like to know if it is possible to modify the resulting calculation of a WRAP_CONTENT height without copying and pasting its parent onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) implementation.

Let's say that my WRAP_CONTENT calculation is equals to parent's resulting calculation + 16dp.


Solution

  • In your custom view, let the super do its work then modify the results:

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(measuredWidth,measuredHeight + 16)
    }
    

    (Here 16 is 16px, so you would have to do the conversion for 16dp if that's what you want.)

    See View#setMeasuredDimension.