Android custom TextView implements text content to automatically adjust font size to fit textview size

Source: Internet
Author: User

Recent Contacts small screen machine contact name display--longer than the boundary font size is smaller

/**  *  custom TextView, text content automatically adjusts font size to fit textview size   *  @author  yzp  */   public class AutoFitTextView extends TextView {       private Paint mTextPaint;      private float  Mtextsize;        public autofittextview (Context context)  {          super (context);       }        public autofittextview (Context context,  attributeset attrs)  {          super (context ,  attrs);      }        /**       * re size the font so the specified text  fits in tHe text box assuming the      * text box is  the specified width.      *        *  @param  text      *  @param  textWidth       */      private void refittext (String  Text, int textviewwidth)  {          if  ( text == null | |  textviewwidth <= 0)                return;          mtextpaint = new  paint ();           mtextpaint.set (This.getPaint ());           int availabletextviewwidth = getwidTh ()  - getpaddingleft ()  - getpaddingright ();           float[] charswidtharr = new float[text.length ()];           rect boundsrect = new rect ();           mtextpaint.gettextbounds (Text, 0, text.length (),  Boundsrect);          int textwidth =  Boundsrect.width ();          mtextsize =  GetTextSize ();          while  (textWidth >  availabletextviewwidth)  {               mTextSize -= 1;               mtextpaint.settextsize (mtextsize);               textwidth =  Mtextpaint.gettextwidths (Text, charswidtharr);           }          this.settextsize (TypedValue.COMPLEX_UNIT_PX ,  mtextsize);       }        @ Override      protected void ondraw (Canvas canvas)  {           super.ondraw (Canvas);           refittext (This.gettext (). toString (),  this.getwidth ());       }  }  

  

Android custom TextView implements text content to automatically adjust font size to fit textview size

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.