Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a minimum width (in characters) for a TextView?

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!

like image 550
If This Is Art Avatar asked Jul 06 '10 17:07

If This Is Art


People also ask

How do I limit characters in TextView?

you can extend the TextView class and overwrite the setText() function. In this function you check for text length or word cound. Better than counting the text length or the word cound a better way would be to use the "maxLines" attribute along with "ellipsize" attribute to attain the desired effect.

How do I Auto Resize TextView?

To use preset sizes to set up the autosizing of TextView in XML, use the android namespace and set the following attributes: Set the autoSizeText attribute to either none or uniform. none is a default value and uniform lets TextView scale uniformly on horizontal and vertical axes.

What is EMS in TextView?

ems is a unit of measurement. The name em was originally a reference to the width of the capital M. It sets the width of a TextView/EditText to fit a text of n 'M' letters regardless of the actual text extension and text size. Eg : android:ems Makes the EditText be exactly this many ems wide.


2 Answers

try this:

android:layout_width="wrap_content" android:minEms="2" 
like image 127
Adrian Avatar answered Oct 08 '22 03:10

Adrian


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); 
like image 29
pforhan Avatar answered Oct 08 '22 02:10

pforhan