Reputation: 39731
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
Upvotes: 11
Views: 7286
Reputation: 5140
Here is a good packaged solution to auto-fit text: https://github.com/grantland/android-autofittextview
Upvotes: 0
Reputation: 5140
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);
}
}
}
Upvotes: 5
Reputation: 24235
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);
}
Upvotes: 11
Reputation: 1821
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.
Upvotes: 0