0

I have a simple EditText with layout_width="wrap_content". There are no paddings or margins in attributes. Here is a full example:

    <EditText
        android:id="@+id/maskPrefix"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="3"
        android:inputType="text|textCapCharacters|textNoSuggestions"
        android:maxLength="5"
        android:maxLines="1"
        android:nextFocusDown="@+id/maskNum"
        android:text="GA"
        android:textSize="18sp"
        tools:ignore="LabelFor" />

Everything is fine but... But:

  1. When I set ems to 1, it is about 1 char wide;
  2. When I set ems to 2, It is about 2.5 chars wide;
  3. When I set ems to 3, It is about 4.5 chars wide;
  4. When I set ems to 4, It is about 6 chars wide;
  5. When I set ems to 5, It is about 10 chars wide;
  6. When I set ems to 10, It is about 20 chars wide;

If I remove android:ems and instead set max width via android:maxLength, then everything is appropriate width. But I need both attributes.

Why is my EditText width wrong? What's with this mysterious multiplier? I use Theme.AppCompat.Light.NoActionBar, latest android studio (2.2.2) and compile with

compile "com.android.support:support-v4:25.0.1"
compile 'com.android.support:appcompat-v7:25.0.1'

Testing with Android 6 in Nexus 5.

What option or attribute could mess android:ems so badly?

UPD. Link to this question does not solve my problem in any way. Also, it is absolutely correct to set both android:textSize and android:ems. I want letters of my text to be x sp large and I want my EditText to be y chars wide.

Community
  • 1
  • 1
Jehy
  • 4,729
  • 1
  • 38
  • 55
  • You are setting both `text_size` and `ems`. Check this http://stackoverflow.com/questions/10275348/what-is-androidems-attribute-in-edit-text – Chisko Nov 30 '16 at 16:01
  • @Chisko Yup, I set both because I need both. And your link without any explanation is pretty useless. Seems like you thought that those were values for the same purpose. Then check your own link once more ;) – Jehy Nov 30 '16 at 23:26

1 Answers1

3

Okay, I found the culprit. I thought that ems size x will be always the same for all characters. But I completely forgot that we have monospace and proportional fonts. And when we set ems to some x, it will be x*y where y is the width of the widest letter (usually M). But width of other letters will be smaller. It is clear on this picture:

M is wider then 1

"M" letters is much wider then "1"!

Solution: we can simply switch to monospace font, like serif-monospace:

monospace font is cool

Jehy
  • 4,729
  • 1
  • 38
  • 55