当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 自定义TextView实现文本内容自动调整字体大小

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

2019年07月24日  | 移动技术网移动技术  | 我要评论

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

/** 
 * 自定义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()); 
  } 
} 

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网