Have TextView scale its font size to fill parent?
Is there a way to have a TextView pick a font size such th开发者_C百科at it fills whatever space it has available? For example:
<LinearLayout
layout_width="fill_parent"
layout_height="50dip" >
<TextView
layout_width="fill_parent"
layout_height="fill_parent"
textSize="scale?" />
</LinearLayout>
Thanks
No, there is not built in font scaling in a TextView
. You could overload the onDraw()
method in a child of TextView
, but TextView
does not support scaling the text automatically.
Take a look at this other question.
Just to update, from API 26 (Android 8.0) TextViews has an attribute to scale text on horizontal and vertical axes
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:autoSizeTextType="uniform" />
Check it at Autosizing TextViews
As in the answer Nick Campion quoted, I used a loop and a static layout to iterate to the correct size. My requirements were to fit the width and use no more than one line (no ellipses):
int i = 0;
while(i < 2) {
layout = new StaticLayout(text, textPaint, w, Alignment.ALIGN_NORMAL, 1, 0, true);
i = layout.getLineCount();
textSize += 2;
textPaint.setTextSize(textSize);
}
textPaint.setTextSize(textSize*0.95f);
精彩评论