Auto Scale Text Size
I'm looking for a way to when I change a screen size it will proportionally resize the text. Currently I tried Auto Scale TextView Text to Fit within Bounds but it doesn't seems t
Solution 1:
You don't need to call AutoResizeTextView test
, you can say TextView
since the class extends TextView
. I don't see why you'd need to call resizeText()
either.
Either way, here's a custom class I like to use to auto re-size text.
publicclassAutoFitTextViewextendsTextView {
publicAutoFitTextView(Context context) {
super(context);
init();
}
publicAutoFitTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
privatevoidinit() {
maxTextSize = this.getTextSize();
if (maxTextSize < 35) {
maxTextSize = 30;
}
minTextSize = 20;
}
privatevoidrefitText(String text, int textWidth) {
if (textWidth > 0) {
intavailableWidth= textWidth - this.getPaddingLeft()
- this.getPaddingRight();
floattrySize= maxTextSize;
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
while ((trySize > minTextSize)
&& (this.getPaint().measureText(text) > availableWidth)) {
trySize -= 1;
if (trySize <= minTextSize) {
trySize = minTextSize;
break;
}
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
}
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
}
}
@OverrideprotectedvoidonTextChanged(final CharSequence text, finalint start,
finalint before, finalint after) {
refitText(text.toString(), this.getWidth());
}
@OverrideprotectedvoidonSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w);
}
}
@OverrideprotectedvoidonMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
intparentWidth= MeasureSpec.getSize(widthMeasureSpec);
refitText(this.getText().toString(), parentWidth);
}
publicfloatgetMinTextSize() {
return minTextSize;
}
publicvoidsetMinTextSize(int minTextSize) {
this.minTextSize = minTextSize;
}
publicfloatgetMaxTextSize() {
return maxTextSize;
}
publicvoidsetMaxTextSize(int minTextSize) {
this.maxTextSize = minTextSize;
}
privatefloat minTextSize;
privatefloat maxTextSize;
}
Solution 2:
Good news! Google introduced Autosizing TextView support in Android O. It will be also included in support librararies.
https://developer.android.com/preview/features/autosizing-textview.html
Solution 3:
I use this, proportionally at the width of the screen.
DisplayMetricsdisplaymetrics=newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
width_screen=displaymetrics.widthPixels;
Mytext.setTextSize(TypedValue.COMPLEX_UNIT_PX, (width_screen/CONST));
the CONST is a number I use for to scale the font, in the dimension I want. It works for my needs.
Post a Comment for "Auto Scale Text Size"