Android改变字体大小,适应区域宽度
2016-04-21 12:06
555 查看
Android改变字体大小,适应区域宽度
在Android中显示文字一般使用的是TextView,有时候我们需要全部显示,但是TextView长度固定,在不换行的前提下,动态改变字体的大小,适应文字所在区域的大小代码块语法遵循标准markdown代码,例如:
public class AutoWidthTextView extends TextView { // Attributes private Paint testPaint; private float cTextSize; public AutoWidthTextView(Context context, AttributeSet attrs) { super(context, attrs); } /** * 在此方法中学习到:getTextSize返回值是以像素(px)为单位的,而setTextSize()是以sp为单位的, * 因此要这样设置setTextSize(TypedValue.COMPLEX_UNIT_PX, size); */ private void refitText(String text, int textWidth) { if (textWidth > 0) { testPaint = new Paint(); testPaint.set(this.getPaint()); //获得当前TextView的有效宽度 int availableWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight(); float[] widths = new float[text.length()]; Rect rect = new Rect(); testPaint.getTextBounds(text, 0, text.length(), rect); //所有字符串所占像素宽度 int textWidths = rect.width(); cTextSize = this.getTextSize();//这个返回的单位为px while(textWidths > availableWidth){ cTextSize = cTextSize - 1; testPaint.setTextSize(cTextSize);//这里传入的单位是px textWidths = testPaint.getTextWidths(text, widths); } this.setTextSize(TypedVal 98b8 ue.COMPLEX_UNIT_PX, cTextSize);//这里制定传入的单位是px } } ; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); refitText(getText().toString(), this.getWidth()); } }
相关文章推荐
- 《android开发必知的50个诀窍》笔记Hack-2
- Android 冷启动 热启动 测试
- android倒计时,使用CountDownTimer
- 使用git hash提交android工程
- Android控件布局属性全解
- Android: LG G3无法连接Mac的解决办法
- android学习笔记(一)
- Android Studio不能获取远程依赖包的解决方法
- 一道题目带你充分理解Android Activity四大启动模式
- Android控件属性大全
- Android 开发问题总结系列一
- android开发-mvp模式理解
- android 使用Notification弹多个通知时,点击跳转intent取值时总是最后一个
- android progressBar 自定义 进度颜色
- 我的Android进阶之旅------>解决AES加密报错:java.security.InvalidKeyException: Unsupported key size: 18 bytes
- Android 使用Drawable实现圆角与圆形图案
- android studio批量打包执行
- Android wear开发真机调试报: Android error: Failed to install *.apk on device *: timeout
- android 自学日记(四) ---ActionBar
- Android RecyclerView初探