【发布时间】:2012-04-17 12:53:53
【问题描述】:
是否可以指定 TextView 的任何属性以使其文本(字体大小)动态缩放以适应 TextView? (类似于 iPhone 的自动缩小功能。)
如果没有,是否有任何人遇到或想出的好的、简单的解决方案来解决这个问题? (这样它也适用于非英语语言。)
【问题讨论】:
标签: android textview android-textattributes
是否可以指定 TextView 的任何属性以使其文本(字体大小)动态缩放以适应 TextView? (类似于 iPhone 的自动缩小功能。)
如果没有,是否有任何人遇到或想出的好的、简单的解决方案来解决这个问题? (这样它也适用于非英语语言。)
【问题讨论】:
标签: android textview android-textattributes
根据 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,只需使用与上面完全相同的代码,但扩展 Button 而不是 TextView。
【讨论】:
FontFitTextView 类是TextView 的扩展,所以你照常使用setText(...) 方法。