android edittext字体间隔,android Edittext内容字体大小动态变化

转自:edittext内容随字体大小动态变化,具体代码如下:

package com.yitong.mbank.android.views;

import android.content.Context;

import android.graphics.Paint;

import android.graphics.Paint.FontMetrics;

import android.util.AttributeSet;

import android.widget.EditText;

public class AutoAdjustSizeEditText extends EditText {

private static float DEFAULT_MIN_TEXT_SIZE = 10; // 最小的字体大小

private static float DEFAULT_MAX_TEXT_SIZE = 20;// 验证大部分手机情况下无效值

// Attributes

private Paint testPaint;

private float minTextSize, maxTextSize;

public AutoAdjustSizeEditText(Context context, AttributeSet attrs) {

super(context, attrs);

initialise();

}

private void initialise() {

testPaint = new Paint();

testPaint.set(this.getPaint()); // 获取模拟的paint

// 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();// 获取改TextView的画布可用大小

float trySize = maxTextSize;

float scaled = getContext().getResources().getDisplayMetrics().scaledDensity;

testPaint.setTextSize(trySize * scaled);// 模拟注意乘以scaled

while ((trySize > minTextSize)

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

trySize -= 2;

FontMetrics fm = testPaint.getFontMetrics();

float scaled1 = (float) (this.getHeight() / (Math

.ceil(fm.descent - fm.top) + 2));

float scaled2 = (float) ((testPaint.measureText(text) / availableWidth));

if (scaled1 >= 1.75 & scaled1 >= scaled2) {// 注意1.75是三星s4 小米3

// 的适合数值(当然包括我的联想了)

break;

}

if (trySize <= minTextSize) {

trySize = minTextSize;

break;

}

testPaint.setTextSize(trySize * scaled);

}

this.setTextSize(trySize);// 等同于this.getPaint().set(trySize*scaled);

}

};

@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);

}

}

}

然后直接在你的xml布局文件中这样使用:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值