Search code examples
androidtextviewandroid-view

Set Padding of TextView depending on Content height of TextView


I currently have a textview with a paddingBottom of 20dp. I want to reduce this padding if the text within the textView is long enough to otherwise get cut off at the bottom.

Here's a diagram illustrating the behavior I want: enter image description here

However, I'm not sure where to call setPadding(). Can someone recommend me an approach for getting this behavior of a dynamic bottom padding?


Solution

  • I ended up creating a custom Layout that contained my textView, and overrode its onMeasure() method. The custom layout was set with height='wrap_content'.

    The system passes in the available height to this layout's onMeasure() method. So here, I measured my child textView's height with

    textView.onMeasure() int preferredHeight = textView.getMeasuredHeight()

    If its preferred height was larger than what my custom view had available to it (minus the bottom padding), I removed the bottom padding with setPadding(). Otherwise, I added the padding.