自適應width TextView

今天在做一個列表的時候,發現某個textView無法擠下去,


就感覺特別蛋疼,後面網上發現有個適應高度的代碼:

原文鏈接:http://jeffreysambells.com/2010/04/04/android-textview-with-auto-sized-content

protected void onDraw (Canvas canvas) {
		super.onDraw(canvas);
		if (fit) _shrinkToFit();
	}
	
	protected void _shrinkToFit() {
		
		int height = this.getHeight();
		int lines = this.getLineCount();
		Rect r = new Rect();
		int y1 = this.getLineBounds(0, r);
		int y2 = this.getLineBounds(lines-1, r);
		
		float size = this.getTextSize();
		if (y2 > height && size >= 8.0f) {
			this.setTextSize(size - 2.0f);
			_shrinkToFit();
		}
		
	}
所以自己就自定義了一個View繼承於TextView,代碼:

public class AutoFitTextView extends TextView {
	
	public AutoFitTextView(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}
	public AutoFitTextView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}
	public AutoFitTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		autoFitWidth();
	}
	
	/**
	 * 自適應寬度
	 */
	public void autoFitWidth() {
		int lineCount = getLineCount();
		float fontSize = this.getTextSize();
		if(lineCount > 1) {
			this.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize - 2.0f);
			autoFitWidth();
		}
	}
}
效果:


那個自適應高度的setTextSize,有個bug,因爲從getTextSize返回的是px,而setTextSize是默認的sp,所以這裏需要注意下



發佈了86 篇原創文章 · 獲贊 53 · 訪問量 65萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章