Android编程实现自动调整TextView字体大小以适应文字长度的方法
本文实例讲述了Android编程实现自动调整TextView字体大小以适应文字长度的方法。分享给大家供大家参考,具体如下:
packagecom.test.android.textview;
importandroid.content.Context;
importandroid.graphics.Paint;
importandroid.util.AttributeSet;
importandroid.widget.TextView;
publicclassCustomTextViewextendsTextView{
privatestaticfloatDEFAULT_MIN_TEXT_SIZE=10;
privatestaticfloatDEFAULT_MAX_TEXT_SIZE=20;
//Attributes
privatePainttestPaint;
privatefloatminTextSize;
privatefloatmaxTextSize;
publicCustomTextView(Contextcontext,AttributeSetattrs){
super(context,attrs);
initialise();
}
privatevoidinitialise(){
testPaint=newPaint();
testPaint.set(this.getPaint());
//maxsizedefaultstotheintiallyspecifiedtextsizeunlessitis
//toosmall
maxTextSize=this.getTextSize();
if(maxTextSize<=DEFAULT_MIN_TEXT_SIZE){
maxTextSize=DEFAULT_MAX_TEXT_SIZE;
}
minTextSize=DEFAULT_MIN_TEXT_SIZE;
}
/**
*Resizethefontsothespecifiedtextfitsinthetextbox*assuming
*thetextboxisthespecifiedwidth.
*/
privatevoidrefitText(Stringtext,inttextWidth){
if(textWidth>0){
intavailableWidth=textWidth-this.getPaddingLeft()-
this.getPaddingRight();
floattrySize=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
protectedvoidonTextChanged(CharSequencetext,intstart,intbefore,
intafter){
super.onTextChanged(text,start,before,after);
refitText(text.toString(),this.getWidth());
}
@Override
protectedvoidonSizeChanged(intw,inth,intoldw,intoldh){
if(w!=oldw){
refitText(this.getText().toString(),w);
}
}
}
希望本文所述对大家Android程序设计有所帮助。