自适应width TextView

本文介绍了一种自定义Android TextView的方法,使其能够自动调整文本大小以适应视图的高度和宽度。通过递归减小字体大小直到文本能完全显示,解决了多行文本布局问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值