Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<LinearLayout
  layout_width="100dip"
  layout_height="50dip">

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

</LinearLayout>

Thanks

like image 214
user291701 Avatar asked Aug 31 '11 15:08

user291701


2 Answers

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);
}
like image 186
Ronnie Avatar answered Oct 08 '22 22:10

Ronnie


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);
        }
    }
}
like image 24
Mason Lee Avatar answered Oct 08 '22 22:10

Mason Lee