欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

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

时间:2021-04-30 10:11:15|栏目:Android代码|点击:

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

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

上一篇:android通知栏的实现方法分析

栏    目:Android代码

下一篇:Android支付宝和微信支付集成

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

本文地址:http://www.codeinn.net/misctech/111674.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有