TextView
の境界(X次元とY次元の両方)に収まるように、複数行のテキストのサイズを変更するメソッドを作成しようとしていTextView
ます。
現在、私は何かを持っていますが、テキストの最初の文字/文字だけがの寸法を満たすようにテキストのサイズを変更するだけですTextView
(つまり、最初の文字だけが表示され、巨大です)。TextViewの境界内にテキストのすべての行を収めるために必要です。
これが私がこれまでに持っているものです:
public static void autoScaleTextViewTextToHeight(TextView tv)
{
final float initSize = tv.getTextSize();
//get the width of the view's back image (unscaled)....
float minViewHeight;
if(tv.getBackground()!=null)
{
minViewHeight = tv.getBackground().getIntrinsicHeight();
}
else
{
minViewHeight = 10f;//some min.
}
final float maxViewHeight = tv.getHeight() - (tv.getPaddingBottom()+tv.getPaddingTop())-12;// -12 just to be sure
final String s = tv.getText().toString();
//System.out.println(""+tv.getPaddingTop()+"/"+tv.getPaddingBottom());
if(minViewHeight >0 && maxViewHeight >2)
{
Rect currentBounds = new Rect();
tv.getPaint().getTextBounds(s, 0, s.length(), currentBounds);
//System.out.println(""+initSize);
//System.out.println(""+maxViewHeight);
//System.out.println(""+(currentBounds.height()));
float resultingSize = 1;
while(currentBounds.height() < maxViewHeight)
{
resultingSize ++;
tv.setTextSize(resultingSize);
tv.getPaint().getTextBounds(s, 0, s.length(), currentBounds);
//System.out.println(""+(currentBounds.height()+tv.getPaddingBottom()+tv.getPaddingTop()));
//System.out.println("Resulting: "+resultingSize);
}
if(currentBounds.height()>=maxViewHeight)
{
//just to be sure, reduce the value
tv.setTextSize(resultingSize-1);
}
}
}
問題はの使用にあると思いますtv.getPaint().getTextBounds(...)
。テキストのサイズがの幅または高さよりもはるかに大きい場合でも、テキストの境界には常に小さい数値が返されます...および値に比べて小さいtv.getWidth()
...。tv.getHeight()
TextView