2012-12-25 150 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); 
    }