Calvin Rai
Calvin Rai

Reputation: 876

How do we set a custom line height in a TextView?

I am working on a custom TextView where we are highlighting certain words in the String with a green background drawable. The drawable is dependent on the line height for the word it is highlighting and will draw itself according to the top and bottom of the particular line it is on, as shown below:

enter image description here

Now, if we zoom into the word that is highlighted, you can see that I've drawn the baseline in red, the top line in blue, and the bottom line in yellow. Per design, the top line (blue) should be 14px from the baseline and the bottom line (yellow) should be 8px from the baseline. The total line height, therefore, is 22px.

enter image description here

The green drawable will automatically extend its top to the top of the line (blue) and its bottom to the bottom of the line (yellow).

The problem is, when I try to set the lineHeight attribute in XML or programmatically, it doesn't get set correctly and you can see that here:

enter image description here

The lineHeight is 22px, but you can see that the line's top and bottom edges aren't positioned correctly. I need the TextView to correctly position the top of each line to the blue line and the bottom of each line to the yellow line.

My question is: Is there anywhere to specify the lineHeight or modify the TextView so that it appears exactly like the design, as shown in the first two screenshots?

The desired result is that the top of the line should be about 14px from the baseline and the bottom of the line should be about 8px from the baseline, totaling a 22px line height.

Can we do this manually in Android and if so, how?

These are some of the resources I've been working through:

  1. https://suragch.medium.com/meaning-of-top-ascent-baseline-descent-bottom-and-leading-in-androids-fontmetrics-c80cf019aef5
  2. Meaning of top, ascent, baseline, descent, bottom, and leading in Android's FontMetrics
  3. https://developpaper.com/how-to-use-android-text-baseline-algorithm/
  4. Truly top-aligning text in Android TextView

...but they aren't exactly what I need.

Upvotes: 1

Views: 660

Answers (0)

Related Questions