今天在做一个列表的时候,发现某个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,所以这里需要注意下