33

I've had a good search for this on here and can't find a solution.

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

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

I don't mind if this is done in XML or code - I just want to avoid having to set the width of a TextView in pixels!

Thanks for any possible solutions; Please ask if I've missed out any important info!

If This Is Art
  • 613
  • 1
  • 8
  • 13

6 Answers6

73

try this:

android:layout_width="wrap_content"
android:minEms="2"
Adrian
  • 764
  • 6
  • 3
23

Ems works if your font is monospace. For proportional fonts, you want it the width of two '0's, not two 'm's. You can fall back to TextPaint.measureText like so:

float measureText = zip.getPaint().measureText("00000");
zip.setWidth(zip.getPaddingLeft() + zip.getPaddingRight() + (int) measureText);
pforhan
  • 807
  • 8
  • 12
3

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"));

Do not forget to specify text size in your TextPaint object
In measureText enter longest possible string you're expecting to see (I've written "-88.88" assuming my text can handle positive or negative numbers below 100 with 2 digits after comma)

Andriy Shpek
  • 141
  • 2
  • 10
0

I think you're looking for the getTextBounds() method in the Paint class. Didn't try it myself tho.

Zsombor Erdődy-Nagy
  • 16,734
  • 16
  • 75
  • 101
0

Simple solution, set typeface of your textview as Monospace.

android:typeface="monospace"
Kuldeep Sakhiya
  • 3,124
  • 1
  • 17
  • 17
-3

Use android:maxLength attribute of TextView.Please read this

Shashank_Itmaster
  • 2,501
  • 5
  • 28
  • 54