1

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

字符串 1:“wwwwwwwww”

字符串 2:“iiiiiiiiii”

在 android string1 比 string 2 大得多,因为“i”比“w”消耗更少的视觉空间

4

2 回答 2

2

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

于 2012-12-25T17:40:35.793 回答
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());
        }
    }

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

@Override
     public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        changeFontSize(editText, 0, 22, 4);
     }
于 2013-06-26T15:17:29.577 回答