Set width of TextView in terms of characters

AndroidWidthTextview

Android Problem Overview


Really looking for an answer to this.

Want to set the width of a TextView based on a number or characters. So if I want it to always be 3 characters wide, I could set that and it will adjust based on the textSize setting. Without this, I have to set a width to 50dip or something, which may or may not be right depending on the font size.

Android Solutions


Solution 1 - Android

Answering my own question...

And the winner is: set the minEms attribute (android:minEms) !!!

So "ems" it turns out refers to the size of the widest character, typically an "M", get it? So setting minEms to an integer value say 3, on an EditText or TextView should ensure it's at least 3 characters wide. You can set the maxEms as well.

So Kyle's answer on this thread, although wrong, caused me to find the answer, so thanks Kyle.

Solution 2 - Android

ems, contrary to popular beliefs (or at least from most thread about ems here), is not based from the width of a single 'M'.

It was originally like that in typography, but in digital medium, including Android, its meaning was shifted to the size of the typeface used, or in other word, its height (excluding any padding for accents/diacritics).

So that means when you specify the ems for a TextView, it will used its textSize as a base and multiply it by the ems specified.

As a sample, if you set a 16sp TextView's ems to 4, its width will be 64sp wide. You can easily test it by using two TextView (with includeFontPadding set to false) side-by-side inside a ConstraintLayout (to leverage its layout_constraintDimensionRatio).

Solution 3 - Android

Most fonts do not set all character widths to be identical. Courier is perhaps the most used exception to this, but generally look at the difference between an i and an A, for example. This makes what your asking to do a bit of a problem.

Solution 4 - Android

Try using: android:maxLength="3"

This will limit your text to a specific number of characters.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFraggleView Question on Stackoverflow
Solution 1 - AndroidFraggleView Answer on Stackoverflow
Solution 2 - AndroidAndrei StakovView Answer on Stackoverflow
Solution 3 - AndroidmahView Answer on Stackoverflow
Solution 4 - AndroidKyleMView Answer on Stackoverflow