手机
当前位置:查字典教程网 >编程开发 >安卓软件开发 >Android编程实现自动调整TextView字体大小以适应文字长度的方法
Android编程实现自动调整TextView字体大小以适应文字长度的方法
摘要:本文实例讲述了Android编程实现自动调整TextView字体大小以适应文字长度的方法。分享给大家供大家参考,具体如下:packageco...

本文实例讲述了Android编程实现自动调整TextView字体大小以适应文字长度的方法。分享给大家供大家参考,具体如下:

package com.test.android.textview; import android.content.Context; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.TextView; public class CustomTextView extends TextView { private static float DEFAULT_MIN_TEXT_SIZE = 10; private static float DEFAULT_MAX_TEXT_SIZE = 20; // Attributes private Paint testPaint; private float minTextSize; private float maxTextSize; public CustomTextView(Context context, AttributeSet attrs) { super(context, attrs); initialise(); } private void initialise() { testPaint = new Paint(); testPaint.set(this.getPaint()); // max size defaults to the intially specified text size unless it is // too small maxTextSize = 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(); float trySize = maxTextSize; testPaint.setTextSize(trySize); while ((trySize > minTextSize) && (testPaint.measureText(text) > availableWidth)) { trySize -= 1; if (trySize <= minTextSize) { trySize = minTextSize; break; } testPaint.setTextSize(trySize); } this.setTextSize(trySize); } } @Override protected void onTextChanged(CharSequence text, int start, int before, int after) { super.onTextChanged(text, start, before, after); refitText(text.toString(), this.getWidth()); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { if (w != oldw) { refitText(this.getText().toString(), w); } } }

希望本文所述对大家Android程序设计有所帮助。

【Android编程实现自动调整TextView字体大小以适应文字长度的方法】相关文章:

android获取监听SD Card状态的方法

Android应用开发SharedPreferences存储数据的使用方法

Android实现Service重启的方法

android TextView设置中文字体加粗实现方法

android实现字体闪烁动画的方法

Android实现Activities之间进行数据传递的方法

Android启动模拟器报错解决方法

android动态布局之动态加入TextView和ListView的方法

android 分辨率适配的方法

Android编程实现图标拖动效果的方法

精品推荐
分类导航