2011-03-01 15 views
3

我在我的活動中有一個textview字段。它的字體大小爲16. 它的文本是通過代碼設置的。假設如果我有一個大的文本,它應該縮小這個數據(即字體大小減少),而不是去下一行。我該怎麼做?TextView文本縮小到給定的寬度

<TextView android:id="@+id/textView" android:layout_width="400dp" android:layout_height="wrap_content" android:text="" android:textSize="16sp" /> 

回答

9

我通過使用以下根據我的要求創建的方法得到了它。

private void autoScaleTextViewTextToHeight(TextView tv) 
    { 
     String s = tv.getText().toString(); 
     float currentWidth = tv.getPaint().measureText(s); 

     float phoneDensity = this.getResources().getDisplayMetrics().density; 

     while(currentWidth > (REQUIRED_WIDTH * phoneDensity)) {   
      tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, tv.getTextSize() - 1.0f); 
      currentWidth = tv.getPaint().measureText(s); 
     } 
    } 
+0

不錯,非常感謝 – 2014-07-10 05:16:36

0

有沒有好方法。你可以做的是計算你將放置在這個TextView中的文本的大小,並重新調整你的字體大小,直到它適合目標區域。計算大小使用Paint.getTextBounds()。

我在畫布上做了非常類似的繪畫。 requries是一個循環,它會減小字體大小,直到calc-ed大小適合。

1

以下方法採用的TextView作爲參數,並根據給定的TextView

private void adjustTextSize(TextView tv) { 

    float size = tv.getPaint().getTextSize(); 
    TextPaint textPaint = tv.getPaint(); 
    float stringWidth = textPaint.measureText(tv.getText().toString()); 
    int textViewWidth = tv.getWidth(); 
    if(textViewWidth > stringWidth) { 

     float percent = (textViewWidth/stringWidth); 
     textPaint.setTextSize(size*percent); 
    } 
} 

希望這有助於的寬度調節其字體的大小。