This article describes an Android programming implementation that automatically adjusts the TextView font size to fit the length of the text. Share to everyone for your reference, specific as follows:
Package Com.test.android.textview;
Import Android.content.Context;
Import Android.graphics.Paint;
Import Android.util.AttributeSet;
Import Android.widget.TextView;
public class Customtextview extends TextView {private static float default_min_text_size = 10;
private static float default_max_text_size = 20;
Attributes private Paint Testpaint;
private float mintextsize;
private float maxtextsize;
Public Customtextview (context, AttributeSet attrs) {Super (context, attrs);
Initialise ();
private void Initialise () {testpaint = new Paint ();
Testpaint.set (This.getpaint ()); Max size defaults to the intially specified text size unless it is//too small = maxtextsize (
);
if (maxtextsize <= default_min_text_size) {maxtextsize = default_max_text_size;
} mintextsize = Default_min_text_size; }/** * Re size the font so the "specified text fits in the" text box * assuming * the text box is the Specified width. * * private void Refittext (String text, int textWidth) {if (TextWidth > 0) {int availablewidth = TextWidth
-This.getpaddingleft ()-this.getpaddingright ();
float trysize = maxtextsize;
Testpaint.settextsize (trysize); while ((Trysize > Mintextsize) && (testpaint.measuretext (text) > Availablewidth)) {Trysiz
e-= 1;
if (trysize <= mintextsize) {trysize = mintextsize;
Break
} testpaint.settextsize (Trysize);
} this.settextsize (Trysize); } @Override protected void ontextchanged (charsequence text, int start, int before, int after) {Super.onte
Xtchanged (text, start, before, after);
Refittext (Text.tostring (), This.getwidth ()); @Override protected void onsizechanged (int w, int h, int oldw, int oldh) {if (w!= oldw) {Refittext (this
. GetText (). ToString (), W);
}
}
}
I hope this article will help you with your Android programming.