有些产品 就是变态 ios 能实现的 他一定要让 android 实现,android 能实现的 非要ios实现,虽然很气愤,但是终究要实现, 有时候 手机分辨率不同,就会出现文字显示不全,本挤压一点,所以这个我们能尽量显示小一点 ,也没啥关系,因此百度的代码 几乎逻辑差不多的
**
* 作者:${李桂云} on 2017/3/23 21:22
* 邮箱:1343168198.com
*/
public classCustomTextViewextendsTextView {
private static floatDEFAULT_MIN_TEXT_SIZE=10;
private static floatDEFAULT_MAX_TEXT_SIZE=20;
// Attributes
privatePainttestPaint;
private floatminTextSize;
private floatmaxTextSize;
publicCustomTextView(Context context,AttributeSet attrs) {
super(context,attrs);
initialise();
}
private void initialise() {
testPaint=newPaint();
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, 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
protected voidonTextChanged(CharSequence text, intstart, intbefore,
intafter) {
super.onTextChanged(text,start,before,after);
refitText(text.toString(), this.getWidth());
}
@Override
protected void onSizeChanged(intw, inth, intoldw, intoldh) {
if(w != oldw) {
refitText(this.getText().toString(),w);
}
}