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

android editText不按字符限制字符串长度,android,android-edittext,maxlength,Android,Android Edittext,Maxlength,我需要确保输入字符串能够适合我要显示它的行。 我已经知道如何限制字符数,但这不是很好,因为两个字符长度相同的字符串大小不同。。。 例如: 字符串1:“WW” 第二条:“IIIIII” 在android中,string1比String2大得多,因为“i”比“w”占用更少的视觉空间。可以用来分析输入的文本并测量文本当前值的宽度。这是我在TextWatcher函数afterTextChanged中使用的代码。我根据朝日的建议提出了解决方案。我不是专业程序员,所以代码看起来可能很糟糕。请随意编辑它,使其

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

字符串1:“WW”

第二条:“IIIIII”


在android中,string1比String2大得多,因为“i”比“w”占用更少的视觉空间。

可以用来分析输入的文本并测量文本当前值的宽度。

这是我在TextWatcher函数afterTextChanged中使用的代码。我根据朝日的建议提出了解决方案。我不是专业程序员,所以代码看起来可能很糟糕。请随意编辑它,使其更好

//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());
        }
    }
@Override
     public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        changeFontSize(editText, 0, 22, 4);
     }