欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 自定义TextView实现文本内容自动调整字体大小

程序员文章站 2022-10-14 14:24:45
最近做通讯录小屏机 联系人姓名显示--长度超过边界字体变小 /** * 自定义textview,文本内容自动调整字体大小以适应textview的大小...

最近做通讯录小屏机 联系人姓名显示--长度超过边界字体变小

/** 
 * 自定义textview,文本内容自动调整字体大小以适应textview的大小 
 * @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()); 
  } 
} 

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!