是否有TextView的任何属性可以指定,以便其文本(字体大小)动态缩放以适应TextView? (类似于iPhone的自动缩小功能)可能指定TextView文本来缩放以适应TextView?
如果没有,是否有任何人都遇到或想出解决这个问题的好的,简单的解决方案? (并且它也适用于非英语语言。)
是否有TextView的任何属性可以指定,以便其文本(字体大小)动态缩放以适应TextView? (类似于iPhone的自动缩小功能)可能指定TextView文本来缩放以适应TextView?
如果没有,是否有任何人都遇到或想出解决这个问题的好的,简单的解决方案? (并且它也适用于非英语语言。)
继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" />
我意识到这一点的实现可以优化和扩展,但只是想表明一个裸露的骨头为您解决延长或根据需要进行修改d。
哦,如果你需要一个缩小文本来代替TextView的Button,只需使用上面的代码,但是扩展Button而不是TextView。
Worked for me..Thanks .. – bakriOnFire 2014-01-15 14:44:31
如何使用上面的示例在活动中设置文字 – Sanket990 2014-07-14 04:35:42
Hey @ Sanket990,my上面的'FontFitTextView'类是'TextView'的扩展,因此您正常使用'setText(...)'方法。 – 2014-07-14 14:17:40
也许这[链接](http://stackoverflow.com/questions/5033012/auto-scale-textview-text-to-fit-within-bounds)可能是有用的... – Ant4res 2012-04-17 13:02:37
检查此http:// stackoverflow.com/questions/7259016/scale-text-in-a-view-to-fit/7259136#7259136 – Ronnie 2014-03-19 12:18:26