转自:edittext内容随字体大小动态变化,具体代码如下:

package com.yitong.mbank.android.views;import android.content.Context;import android.graphics.Paint;import android.graphics.Paint.FontMetrics;import android.util.AttributeSet;import android.widget.EditText;public class AutoAdjustSizeEditText extends EditText {private static float DEFAULT_MIN_TEXT_SIZE = 10; // 最小的字体大小private static float DEFAULT_MAX_TEXT_SIZE = 20;// 验证大部分手机情况下无效值// Attributesprivate Paint testPaint;private float minTextSize, maxTextSize;public AutoAdjustSizeEditText(Context context, AttributeSet attrs) {super(context, attrs);initialise();}private void initialise() {testPaint = new Paint();testPaint.set(this.getPaint()); // 获取模拟的paint// max size defaults to the intially specified text size unless it is// too smallmaxTextSize = this.getTextSize();// 获取单个字体的像素if (maxTextSize <= DEFAULT_MIN_TEXT_SIZE) {maxTextSize = DEFAULT_MAX_TEXT_SIZE;}minTextSize = DEFAULT_MIN_TEXT_SIZE;};/** * Re size the font so the specified text fits in the text box * assuming * the text box is the specified width. */private void refitText(String text, int textWidth) {if (textWidth > 0) {int availableWidth = textWidth - this.getPaddingLeft()- this.getPaddingRight();// 获取改TextView的画布可用大小        float trySize = maxTextSize;float scaled = getContext().getResources().getDisplayMetrics().scaledDensity;testPaint.setTextSize(trySize * scaled);// 模拟注意乘以scaledwhile ((trySize > minTextSize)&& (testPaint.measureText(text) > availableWidth)) {trySize -= 2;FontMetrics fm = testPaint.getFontMetrics();float scaled1 = (float) (this.getHeight() / (Math.ceil(fm.descent - fm.top) + 2));float scaled2 = (float) ((testPaint.measureText(text) / availableWidth));if (scaled1 >= 1.75 & scaled1 >= scaled2) {// 注意1.75是三星s4 小米3// 的适合数值(当然包括我的联想了)break;}if (trySize <= minTextSize) {trySize = minTextSize;break;}testPaint.setTextSize(trySize * scaled);}this.setTextSize(trySize);// 等同于this.getPaint().set(trySize*scaled);}};@Overrideprotected void onTextChanged(CharSequence text, int start, int before,int after) {super.onTextChanged(text, start, before, after);refitText(text.toString(), this.getWidth());}@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) {if (w != oldw) {refitText(this.getText().toString(), w);}}}

然后直接在你的xml布局文件中这样使用:

 

更多相关文章

  1. Android设备信息管理工具类
  2. android > WiFi > 新建连接
  3. android获取控件的几种方法
  4. android 的Handler处理UI主线程外的耗时操作
  5. android获取指定路径下目录文件
  6. android模拟返回键
  7. android 在SDCard获取图片
  8. 后续:优化
  9. android 从系统相册获取一张图片

随机推荐

  1. Android应用程序启动过程源代码分析(3)
  2. Android Glide加载四周圆角图
  3. MultiDex 遇到的大坑
  4. android 工程,点击图片,在屏幕显示
  5. CheckedTextView 复选框左显示
  6. Android RecyclerView多个Item布局的实现
  7. Android sensor 学习--sensor介绍
  8. Android的权限 permission
  9. 在android获取root权限的方法^_^。
  10. Error:(19, 0) Gradle DSL method not fo