android pain设置字体,Android编程实现自动调整TextView字体大小以适应文字长度的方法...

这是一个关于Android自定义TextView的实现,该TextView能够根据指定的宽度自动调整字体大小,确保文本完全显示。通过设置最大和最小字体大小限制,实现了在不同宽度屏幕上的适配。在`onTextChanged`和`onSizeChanged`回调中调用`refitText`方法,动态计算适合的字体大小。

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

package com.test.android.textview;

import android.content.Context;

import android.graphics.Paint;

import android.util.AttributeSet;

import android.widget.TextView;

public class CustomTextView extends TextView {

private static float DEFAULT_MIN_TEXT_SIZE = 10;

private static float DEFAULT_MAX_TEXT_SIZE = 20;

// Attributes

private Paint testPaint;

private float minTextSize;

private float maxTextSize;

public CustomTextView(Context context, AttributeSet attrs) {

super(context, attrs);

initialise();

}

private void initialise() {

testPaint = new Paint();

testPaint.set(this.getPaint());

// max size defaults to the intially specified text size unless it is

// too small

maxTextSize = this.getTextSize();

if (maxTextSize <= DEFAULT_MIN_TEXT_SIZE) {

maxTextSize = DEFAULT_MAX_TEXT_SIZE;

}

minTextSize = DEFAULT_MIN_TEXT_SIZE;

}

/**

* Re size the font so the specified text fits in the text box * assuming

* the text box is the specified width.

*/

private void refitText(String text, int textWidth) {

if (textWidth > 0) {

int availableWidth = textWidth - this.getPaddingLeft() -

this.getPaddingRight();

float trySize = maxTextSize;

testPaint.setTextSize(trySize);

while ((trySize > minTextSize) &&

(testPaint.measureText(text) > availableWidth)) {

trySize -= 1;

if (trySize <= minTextSize) {

trySize = minTextSize;

break;

}

testPaint.setTextSize(trySize);

}

this.setTextSize(trySize);

}

}

@Override

protected void onTextChanged(CharSequence text, int start, int before,

int after) {

super.onTextChanged(text, start, before, after);

refitText(text.toString(), this.getWidth());

}

@Override

protected void onSizeChanged(int w, int h, int oldw, int oldh) {

if (w != oldw) {

refitText(this.getText().toString(), w);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值