开发者

Scale text in a view to fit?

I don't believe this exists, but wanted to double-check. I'd like to set a TextView's text size such that it would fit within a given width, single line. Example:

<LinearLay开发者_Go百科out
  layout_width="100dip"
  layout_height="50dip">

  <TextView
    layout_width="fill_parent"
    layout_height="wrap_content"
    textSize="fill" 
    text="fit me please!" />

</LinearLayout>

Thanks


You can use the TextUtils.EllipsizeCallback. When the text gets ellipsized this callback is done by the textview. Here you can set text size smaller than the current.

EDIT : Otherwise you can use TextUtils.ellipsize this way

while (mText != TextUtils.ellipsize(mText, textPaint, other params)) { 
    textpaint.setTextSize(textpaint.getTextSize() - 1);
}


This custom function should do it, using TextUtils.ellipsize ...

public static void shrinkTextToFit(float availableWidth, TextView textView,
                                   float startingTextSize, float minimumTextSize) {

    CharSequence text = textView.getText();
    float textSize = startingTextSize;
    textView.setTextSize(startingTextSize);
    while (text != (TextUtils.ellipsize(text, textView.getPaint(),
                                        availableWidth, TextUtils.TruncateAt.END))) {
        textSize -= 1;
        if (textSize < minimumTextSize) {
            break;
        } else {
            textView.setTextSize(textSize);
        }
    }
}


You can always combine the xml layout definition with java and dynamically define the size of the text. You will probably need some calculations and references from the dip units to the pixel density information about the current screen in use, but once done, it should almost guaranteed solve your problem for all cases.


Here is a good packaged solution to auto-fit text: https://github.com/grantland/android-autofittextview

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜