700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > android edittext字体间隔 android Edittext内容字体大小动态变化

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

时间:2023-05-03 00:24:24

相关推荐

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布局文件中这样使用:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。