如何设置 EditText 的固定最小宽度,使其紧紧围绕提示和长度限制的类型内容?

Ste*_*sen 5 android width android-edittext

我想为 an 设置最小固定宽度,EditText以便它既可以包含它的提示,也可以包含键入的、长度受限的内容,例如 2 位数字。

一些细节:

  1. 我希望能够动态地做到这一点,因为我有许多用于不同目的的字段,具有不同的提示(不同语言)和输入长度(一些 2 位数字,其他 4 位数字)。
  2. 提示不一定比输入本身长。提示可以是“dd”或“Day”,输入可以是到数字。
  3. 我不需要同时为提示和内容留出空间;当用户开始输入时提示消失。
  4. 我用了一个扩展自定义字体EditText类,但因为我复制应该处理EditTextPaint

我有这样做的实用方法,但它返回的宽度太窄,因此提示被剪裁。我究竟做错了什么?

EditText 在 XML 中指定如下:

 <EditText
        android:id="@+id/birthday_month"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:hint="@string/birthday_month_hint"
        android:lines="1"
        android:maxLength="2">
Run Code Online (Sandbox Code Playgroud)

在我的活动中,我首先找到 EditText,然后使用Texts.setNiceAndTightWidth(monthEditText, 2)下面定义的(包括辅助方法)准备它:

public class Texts
{

    public static void setNiceAndTightWidth ( EditText editText, int maxInputLength )
    {
        // String of chars to test for widest char.  Include all possible input chars and chars of hint, as we need to make room for hint as well.
        String testChars = String.format("1234568790%s", editText.getHint().toString());

        char widestChar = getWidestChar(editText, testChars);
        String widestString = repeat(widestChar, maxInputLength);

        float widestStringWidth = getTextWidth(editText, widestString);
        int width = (int)(widestStringWidth + 0.5f);

        editText.setWidth(width);

        // This was an experiment but it doesn't help.
        ViewGroup.LayoutParams lp = editText.getLayoutParams();
        lp.width = width;
        editText.setLayoutParams(lp);
    }


    public static char getWidestChar ( TextView textView, String testChars )
    {
        float width, widest = 0;
        char widestChar = '\0';

        // Using Paint properties of TextView, including Fontface, text size, etc.
        Paint paint = new Paint( textView.getPaint() );

        for ( int i = 0 ; i < testChars.length() ; i++ ) {
            width = paint.measureText(testChars, i, i+1);
            if ( width > widest ) {
                widest = width;
                widestChar = testChars.charAt(i);
            }
        }

        return widestChar;
    }

    public static String repeat ( char ch, int length )
    {
        char[] chars = new char[length];
        Arrays.fill(chars, ch);
        String string = String.valueOf(chars);
        return string;
    }

    public static float getTextWidth ( TextView textView, CharSequence text )
    {
        Paint paint = new Paint( textView.getPaint() );
        float width = paint.measureText(text, 0, text.length());
        return width;
    }

}
Run Code Online (Sandbox Code Playgroud)