2012-12-25 108 views
0

我需要确保输入字符串可以适合我要显示它的行。 我已经知道如何限制的字符数,但不是非常好,因为2串用相同的字符长度有differente大小... 对于为例:android editText限制字符串长度不是字符

的String1:“wwwwwwwwww”

String2的: “IIIIIIIIII”

android的字符串1

是不是字符串2要大得多,因为“我”消耗比“W”

回答

1

您可以使用TextWatcher分析文本中输入并Paint较少的视觉空间测量电流的宽度th值电子文本。

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); 
    }