首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

自动调整TextView字体大小以顺应文字长度

2012-08-22 
自动调整TextView字体大小以适应文字长度package me.mcar.parking.controlimport android.content.Contex

自动调整TextView字体大小以适应文字长度

package me.mcar.parking.control;import android.content.Context;import android.graphics.Paint;import android.util.AttributeSet;import android.widget.TextView;public class AutoAjustSizeTextView extends TextView{private static float DEFAULT_MIN_TEXT_SIZE = 10;private static float DEFAULT_MAX_TEXT_SIZE = 16;// Attributesprivate Paint testPaint;private float minTextSize, maxTextSize;public AutoAjustSizeTextView(Context context, AttributeSet attrs){super(context, attrs);initialise();}private void initialise(){testPaint = new Paint();testPaint.set(this.getPaint()); 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);}};@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);}}}

控件使用方法
<me.mcar.parking.control.AutoAjustSizeTextView            android:id="@+id/parklist_item_address"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="left"            android:textColor="#A0A0A0"            android:textSize="12sp" />

热点排行