是否可以指定 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" />
我意识到这个实现可以被优化和扩展,但只是试图展示一个简单的解决方案供您根据需要扩展或修改。
Oh and if you need a Button which shrinks text to fit instead of a TextView, simply use the code exact as above but extend Button instead of TextView.