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!
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.
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.
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.
try this:
android:layout_width="wrap_content" android:minEms="2"
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With