android editText限制字符串长度不是字符

时间:2012-12-25 17:00:56

标签: android android-edittext maxlength

我需要确保输入字符串能够适合我要显示它的行。 我已经知道如何限制字符数但这不是很好,因为具有相同字符长度的2个字符串具有不同的大小... 例如:

String1:“wwwwwwwwww”

String2:“iiiiiiiiii”

android string1中的

远大于字符串2,因为“i”比“w”消耗更少的可视空间

2 个答案:

答案 0 :(得分:2)

您可以使用TextWatcher分析输入的文字,使用Paint来衡量文字当前值的宽度。

答案 1 :(得分:0)

这是我在TextWatcher函数afterTextChanged中用于此目的的代码。我的解决方案是基于Asahi的建议。我不是程序员,所以代码看起来可能很糟糕。随意编辑它以使其更好。

//offset is used if you want the text to be downsized before it reaches the full editTextWidth
    //fontChangeStep defines by how much SP you want to change the size of the font in one step
    //maxFontSize defines the largest possible size of the font (in SP units) you want to allow for the given EditText
    public void changeFontSize(EditText editText, int offset, int maxFontSize, int fontChangeSizeStep) {
        int editTextWidth = editText.getWidth();
        Paint paint = new Paint();

        final float densityMultiplier = getBaseContext().getResources().getDisplayMetrics().density;
        final float scaledPx = editText.getTextSize();
        paint.setTextSize(scaledPx);
        float size = paint.measureText(editText.getText().toString());

        //for upsizing the font
        // 15 * densityMultiplier is subtracted because the space for the text is actually smaller than than editTextWidth itself
        if(size < editTextWidth - 15 * densityMultiplier - offset) {
            paint.setTextSize(editText.getTextSize() + fontChangeSizeStep * densityMultiplier);
            if(paint.measureText(editText.getText().toString()) < editTextWidth - 15 * densityMultiplier - offset) //checking if after possible upsize the text won't be too wide for the EditText
                if(editText.getTextSize()/densityMultiplier < maxFontSize)
                    editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, editText.getTextSize()/densityMultiplier + fontChangeSizeStep);
        }
        //for downsizing the font, checking the editTextWidth because it's zero before the UI is generated
        while(size > editTextWidth - 15 * densityMultiplier - offset && editTextWidth != 0) { 
            editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, editText.getTextSize()/densityMultiplier - fontChangeSizeStep);
            paint.setTextSize(editText.getTextSize());
            size = paint.measureText(editText.getText().toString());
        }
    }

如果您想在加载活动时更改fontSize,这只是一个小建议。如果在OnCreate方法中使用该函数,它将无法工作,因为此时UI尚未定义,因此您需要使用此函数来获得所需的结果。

@Override
     public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        changeFontSize(editText, 0, 22, 4);
     }