Android 自定義TextView實現(xiàn)文本內(nèi)容自動調(diào)整字體大小
更新時間:2017年03月24日 09:12:30 作者:ganchuanpu
本文主要介紹了Android 自定義TextView實現(xiàn)文本內(nèi)容自動調(diào)整字體大小以適應(yīng)TextView的大小的方法。具有很好的參考價值。下面跟著小編一起來看下吧
最近做通訊錄小屏機(jī) 聯(lián)系人姓名顯示--長度超過邊界字體變小
/**
* 自定義TextView,文本內(nèi)容自動調(diào)整字體大小以適應(yīng)TextView的大小
* @author yzp
*/
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);
}
/**
* Re size the font so the specified text fits in the text box assuming the
* text box is the specified width.
*
* @param text
* @param textWidth
*/
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());
}
}
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
Android使用Circular Reveal動畫讓頁面跳轉(zhuǎn)更炫酷
本篇文章主要介紹了Android使用Circular Reveal動畫讓頁面跳轉(zhuǎn)更炫酷,具有一定的參考價值,有興趣的可以了解一下2017-08-08
Android利用Sensor(傳感器)實現(xiàn)水平儀功能
這篇文章主要為大家詳細(xì)介紹了Android利用Sensor傳感器實現(xiàn)水平儀功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02
Android實現(xiàn)短信加密功能(發(fā)送加密短信、解密本地短信)
這篇文章主要介紹了android實現(xiàn)短信加密功能的相關(guān)資料,功能包括發(fā)送加密短信、解密本地短信,感興趣的小伙伴們可以參考一下2016-01-01

