import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
/**固定textview 为单行后,自动对内容进行缩放来适应textview<br>
* 通过循环measure来找到适合值<br>
* 超过10个字符有可能出现超过16ms<br>
* AAS(Auto adjust size)
* @author WenYF
*
*/
public class AASTextView extends TextView {
private static final float INTERVAL_SIZE = 0.33f;
private float DEFAULT_MIN_TEXT_SIZE = 10.f;
private float DEFAULT_MAX_TEXT_SIZE = 16.f;
public void setFontMaxSize(float size){
DEFAULT_MAX_TEXT_SIZE = size;
}
public void setFontMinSize(float size){
DEFAULT_MIN_TEXT_SIZE = size;
}
private float nScale;
private Paint nTextPaint;
/**
* 构建AutoSizeTextView.
*
* @param context
* @param attrs
*/
public AASTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initValues();
}
/**
* 构建AutoSizeTextView.
*
* @param context
*/
public AASTextView(Context context) {
super(context);
initValues();
}
private void initValues(){
nScale = getContext().getResources().getDisplayMetrics().density;
nTextPaint = new Paint();
}
/**
* 当View的Text发生变化后就调用该事件
*
* @param text
* TextView显示的文本
* @param start
* 对文本进行了修改的范围的开始偏移量
* @param lengthBefore
* 被替换的旧的文本长度
* @param lengthAfter
* 替换修改后的文本的长度
*/
@Override
protected void onTextChanged(CharSequence text, int start, int before,
int after) {
super.onTextChanged(text, start, before, after);
refreshText(text.toString(), getWidth());
}
/**
* 当View的Size发生变化后就调用该事件
*
* @param w
* 该View的当前宽度
* @param h
* 该View的当前高度
* @param oldw
* 该View的旧宽度
* @param oldh
* 该View的旧高度
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw) {
refreshText(getText().toString(), w);
}
}
/**
* 重新设定View的TextSize,以便在文本框中显示的文本适合文本框指定的宽度。
*
* @param text
* 显示的文本内容
* @param textWidth
* 文本的宽度
*/
private void refreshText(String text, int textWidth) {
if (textWidth > 0) {
int availableWidth = textWidth - getPaddingLeft()
- getPaddingRight();
float trySize = getTextSize() > DEFAULT_MAX_TEXT_SIZE
? DEFAULT_MAX_TEXT_SIZE : getTextSize();
while ((trySize > DEFAULT_MIN_TEXT_SIZE)
&& (getTextWidth(text, trySize) > availableWidth)) {
trySize -= INTERVAL_SIZE;
if (trySize <= DEFAULT_MIN_TEXT_SIZE) {
trySize = DEFAULT_MIN_TEXT_SIZE;
break;
}
}
this.setTextSize(trySize);
}
}
/**
* 获取Text的宽度
*
* @param text
* @param size
* @return
*/
private float getTextWidth(String text, float size) {
float w;
//Log.i("AASTextview", "size = " + size);
//Log.i("AASTextview", "scale = " + nScale);
nTextPaint.set(getPaint());
nTextPaint.setTextSize(size * nScale);
w = nTextPaint.measureText(text);
//Log.i("AASTextview", "w = " + w);
return w;
}
}
布局文件中配置
<com.pingyijinren.common.view.text.AASTextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="36sp"
android:text="dsfsdsadsaddsaddsf" >
</com.pingyijinren.common.view.text.AASTextView>