How to set the minimum width (in characters) for a TextView?

I had a good search for this here and cannot find a solution.

I have a TextView in a RelativeLayout that contains an integer. The number will range from 1 to 99 - can someone tell me how the size of the TextView is so that its width is always the width of the string "99", even if it contains only "1"?

I need this because the position of the components to the right of this TextView depends on its width, so all positions depend on how many digits are contained in the TextView.

I don't mind if it's done in XML or code - I just want to avoid setting the width of the TextView in pixels!

Thanks for any possible solutions; Please ask if I have missed any important information!

+22
android text rendering
Jul 06 '10 at 17:35
source share
5 answers

try the following:

android:layout_width="wrap_content" android:minEms="2" 
+55
Jun 04 2018-11-11T00:
source share

Ems works if your font is monospaced. For proportional fonts, you need the width of two "0", not two. You can return to TextPaint.measureText as follows:

 float measureText = zip.getPaint().measureText("00000"); zip.setWidth(zip.getPaddingLeft() + zip.getPaddingRight() + (int) measureText); 
+18
May 11 '12 at 19:38
source share

The best way is to use TextPaint . Here is a simple example:

 TextPaint textPaint = new TextPaint(); textPaint.setTextSize(yourTextView.getTextSize()); yourTextView.setMinWidth((int) textPaint.measureText("-88.88")); 

Remember to specify the size of the text in your TextPaint
In measureText enter the longest line that you expect to see (I wrote "-88.88", assuming my text can handle positive or negative numbers below 100 with two decimal places)

+1
May 13, '19 at 16:38
source share

I think you are looking for the getTextBounds () method in the Paint class. I have not tried it myself.

0
Feb 22 '11 at 7:44
source share

Use android: maxLength attribute in TextView. Please read this

-2
Feb 22 2018-11-22T00:
source share



All Articles