栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

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

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

 
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); 
  } 
   
  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()); 
  } 
} 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/159272.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号