2011-03-01 14 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

ありがとう –

0

いい方法はありません。あなたができることは、このTextViewに配置しようとしているテキストのサイズを計算し、それが目的の領域に収まるまでフォントサイズを再調整することです。 Calcのサイズには、Paint.getTextBounds()を使用します。

私はキャンバスでの描画に非常によく似ています。計算されたサイズが適切になるまでフォントサイズを減少させるループが必要です。

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

このことができます希望の幅に応じてフォントのサイズを調整します。

関連する問題