android 字符串根据textview宽度 自动调整自身大小

这个`CustomTextView`类通过重写`onDraw`方法,在每次绘制时根据文本内容和TextView的宽度动态调整字体大小,确保文字能完全显示在区域内。在`refitText`方法中,不断减小字体大小直到文本宽度小于等于可用宽度。

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

package com.example.testtextview;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;


/**
 * 可根据字符串所占的长度(非字符串长度)自动缩小字体大小, 以适应显示区域的宽度
 * 
 * 
 */
public class CustomTextView extends TextView {


// Attributes
private Paint testPaint;
private float cTextSize;


public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}


/**
* Re size the font so the specified text fits in the text box * assuming
* the text box is the specified width.
* 在此方法中学习到:getTextSize返回值是以像素(px)为单位的,而setTextSize()是以sp为单位的,
* 因此要这样设置setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
*/
private void refitText(String text, int textWidth) {
if (textWidth > 0) {
testPaint = new Paint();
testPaint.set(this.getPaint());
// 获得当前TextView的有效宽度
int availableWidth = textWidth - this.getPaddingLeft()
- this.getPaddingRight();
float[] widths = new float[text.length()];
Rect rect = new Rect();
testPaint.getTextBounds(text, 0, text.length(), rect);
// 所有字符串所占像素宽度
int textWidths = rect.width();
cTextSize = this.getTextSize();// 这个返回的单位为px
while (textWidths > availableWidth) {
cTextSize = cTextSize - 1;
testPaint.setTextSize(cTextSize);// 这里传入的单位是px
textWidths = testPaint.getTextWidths(text, widths);
}
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, cTextSize);// 这里制定传入的单位是px
}
};


@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
refitText(getText().toString(), this.getWidth());
}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值