类似拨号盘的EditText,随文字数量的增加,动态改变文字的大小,比较简单。
public class AutoSizeEditText extends EditText {
private static float DEFAULT_MIN_TEXT_SIZE = 2; // 最小的字体大小
private float minTextSize, maxTextSize;
public AutoSizeEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
maxTextSize = this.getTextSize();// 获取单个字体的像素
minTextSize = DEFAULT_MIN_TEXT_SIZE;
}
public void resizeText(TextView textView, float originalTextSize, float minTextSize) {
final Paint paint = textView.getPaint();
final int width = textView.getWidth();
if (width == 0) {
return;
}
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, originalTextSize);
float ratio = width / paint.measureText(textView.getText().toString());
if (ratio <= 1.0f) {
textView.setTextSize(
TypedValue.COMPLEX_UNIT_PX, Math.max(minTextSize, originalTextSize * ratio));
}
}
@Override
protected void onTextChanged(CharSequence text, int start, int before,
int after) {
super.onTextChanged(text, start, before, after);
resizeText(this, maxTextSize, minTextSize);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
resizeText(this, maxTextSize, minTextSize);
}
}