テキスト (フォント サイズ) が TextView 内に収まるように動的にスケーリングされるように指定できる TextView のプロパティはありますか? (iPhone の自動縮小機能に似ています。)
そうでない場合、これを解決するために誰かが遭遇した、または思いついた、優れた簡単な解決策はありますか? (そして、英語以外の言語でも機能するように。)
テキスト (フォント サイズ) が TextView 内に収まるように動的にスケーリングされるように指定できる TextView のプロパティはありますか? (iPhone の自動縮小機能に似ています。)
そうでない場合、これを解決するために誰かが遭遇した、または思いついた、優れた簡単な解決策はありますか? (そして、英語以外の言語でも機能するように。)
V4l3ri4 のリンクとそこから生成されたリンクに続いて、TextView の幅に収まるまで TextView 内のテキストを継続的に縮小する次の基本的なソリューションを思いつきました。
public class FontFitTextView extends TextView
{
private float maxTextSizePx;
public FontFitTextView(Context context)
{
super(context);
initialise();
}
public FontFitTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
initialise();
}
public FontFitTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
initialise();
}
/** Sets the maximum text size as the text size specified to use for this View.*/
private void initialise()
{
maxTextSizePx = getTextSize();
}
/** Reduces the font size continually until the specified 'text' fits within the View (i.e. the specified 'viewWidth').*/
private void refitText(String text, int viewWidth)
{
if (viewWidth > 0)
{
TextPaint textPaintClone = new TextPaint();
textPaintClone.set(getPaint());
int availableWidth = viewWidth - getPaddingLeft() - getPaddingRight();
float trySize = maxTextSizePx;
// note that Paint text size works in px not sp
textPaintClone.setTextSize(trySize);
while (textPaintClone.measureText(text) > availableWidth)
{
trySize--;
textPaintClone.setTextSize(trySize);
}
setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
}
}
@Override
protected void onTextChanged(final CharSequence text, final int start, final int lengthBefore, final int lengthAfter)
{
super.onTextChanged(text, start, lengthBefore, lengthAfter);
refitText(text.toString(), getWidth());
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw)
refitText(getText().toString(), w);
}
}
使用例は次のとおりです。
<view
class="com.mycompany.myapp.views.FontFitTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true" />
この実装は最適化および拡張できることは理解していますが、必要に応じて拡張または変更できる必要最小限のソリューションを示しているだけです。
ああ、TextView の代わりにテキストを縮小して収まるようにする Button が必要な場合は、上記とまったく同じコードを使用して、TextView の代わりに Button を拡張します。