您的位置:首页 > 其它

笔记11 | 动态更改TextView的字体大小

2017-09-29 21:07 309 查看


地址



一个常用的知识点:动态设置TextView的大小的工具,需要动态更改的TextView的内容字体的大小,比如设定的TextView的只有一行,宽度只有200dp,内容超过这个之后就缩小字体显示,只能能将字体都显示完全;也就是动态更改的的TextView的字体大小,当TextView的的的内容比较多时缩小显示,当TextView的中的内容比较少时正常显示


目录

图片展示

方法一:重写的TextView

方法二:使用框架Android的autofittextview


图片展示







可以看出来:当文字没有填充的TextView的完全时显示的就是默认的字体,当文字能够完全填充的TextView的并且一行显示不下时,他会默认的缩小文字的字体,当文字再多时,他会默认在末尾省略。


方法一:重写的TextView

此类方法是在的TextView的onTextChanged和onSizeChanged下,根据获取的TextView可容纳的宽度来计算一个靠近可容纳的最大字体宽度,从而来给TextView的设置textsize。

public class CustomTextView extends TextView {

/*
* Even add it by 20170518
* dynamic setting textview's width and textsize Demo
*
*/

/*
* 定义字体大小边界值
*/
private static float DEFAULT_MIN_TEXT_SIZE = 1;
private static float DEFAULT_MAX_TEXT_SIZE = 48;

// Attributes
private Paint testPaint; //此类包含如何绘制的样式和颜色信息
private float minTextSize, TextSize, maxTextSize;

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

private void initialise() {
/*
* limited size
*/
testPaint = new Paint();
testPaint.set(this.getPaint());
TextSize = this.getTextSize();
if (TextSize <= DEFAULT_MIN_TEXT_SIZE) {
TextSize = DEFAULT_MIN_TEXT_SIZE;
}
if (TextSize >= DEFAULT_MAX_TEXT_SIZE) {
TextSize = DEFAULT_MAX_TEXT_SIZE;
}
minTextSize = DEFAULT_MIN_TEXT_SIZE;
maxTextSize = DEFAULT_MAX_TEXT_SIZE;
};

/*
* (non-Javadoc)
* @see android.widget.TextView#onTextChanged(java.lang.CharSequence, int, int, int)
*/
@Override
protected void onTextChanged(CharSequence text, int start, int before,
int after) {
super.onTextChanged(text, start, before, after);
refitText(text.toString(), this.getWidth());
}

/*
* (non-Javadoc)
* @see android.view.View#onSizeChanged(int, int, int, int)
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w);
}
}

private void refitText(String text, int textWidth) {

if (textWidth > 0) {
int availableWidth = textWidth - this.getPaddingLeft()
- this.getPaddingRight();
float trySize = TextSize;
float scaled = getContext().getResources().getDisplayMetrics().scaledDensity;
testPaint.setTextSize(trySize* scaled);//给testPaint设置 dp转为px后的textsize
while ((trySize > minTextSize||trySize<maxTextSize)&&
(testPaint.measureText(text) > availableWidth)
) {
trySize -= 2; //减小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) {
break;
}
if (trySize <= minTextSize) {
trySize = minTextSize;
break;
}else if (trySize >= maxTextSize) {
trySize = maxTextSize;
break;
}
testPaint.setTextSize(trySize* scaled);
}
this.setTextSize(trySize);
}
};
}



方法二:使用框架Android的autofittextview

框架地址:HTTPS://github.com/grantland/android-autofittextview

AutofitTextView:自定义的TextView的并继承系统的的TextView的,然后在绘制组件的时候根据getMaxLines方法获取内容的行数若内容的行数大于1,则缩小文字的字体,然后在尝试获取getMaxLines方法,若内容的行数还是大于1,则缩小文字的字体,直到内容能够一行显示或者是字体缩小大一定的大小,这时候若缩小到一定的大小还是不能一行显示,则尾部省略。

package me.grantland.widget;


import android.content.Context;

import android.util.AttributeSet;

import android.util.TypedValue;

import android.widget.TextView;


/**

* A {@link TextView} that re-sizes its text to be no larger than the width of the view.

*

* @attr ref R.styleable.AutofitTextView_sizeToFit

* @attr ref R.styleable.AutofitTextView_minTextSize

* @attr ref R.styleable.AutofitTextView_precision

*/

public class AutofitTextView extends TextView implements AutofitHelper.OnTextSizeChangeListener {


private AutofitHelper mHelper;


public AutofitTextView(Context context) {

super(context);

init(context, null, 0);

}


public AutofitTextView(Context context, AttributeSet attrs) {

super(context, attrs);

init(context, attrs, 0);

}


public AutofitTextView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

init(context, attrs, defStyle);

}


private void init(Context context, AttributeSet attrs, int defStyle) {

mHelper = AutofitHelper.create(this, attrs, defStyle)

.addOnTextSizeChangeListener(this);

}


// Getters and Setters


/**

    * {@inheritDoc}

   */

@Override

public void setTextSize(int unit, float size) {

super.setTextSize(unit, size);

if (mHelper != null) {

mHelper.setTextSize(unit, size);

}

}


/**

    * {@inheritDoc}

   */

@Override

public void setLines(int lines) {

super.setLines(lines);

if (mHelper != null) {

mHelper.setMaxLines(lines);

}

}


/**

    * {@inheritDoc}

   */

@Override

public void setMaxLines(int maxLines) {

super.setMaxLines(maxLines);

if (mHelper != null) {

mHelper.setMaxLines(maxLines);

}

}


/**

    * Returns the {@link AutofitHelper} for this View.

   */

public AutofitHelper getAutofitHelper() {

return mHelper;

}


/**

    * Returns whether or not the text will be automatically re-sized to fit its constraints.

   */

public boolean isSizeToFit() {

return mHelper.isEnabled();

}


/**

    * Sets the property of this field (sizeToFit), to automatically resize the text to fit its

    * constraints.

   */

public void setSizeToFit() {

setSizeToFit(true);

}


/**

    * If true, the text will automatically be re-sized to fit its constraints; if false, it will

    * act like a normal TextView.

    *

    * @param sizeToFit

   */

public void setSizeToFit(boolean sizeToFit) {

mHelper.setEnabled(sizeToFit);

}


/**

    * Returns the maximum size (in pixels) of the text in this View.

   */

public float getMaxTextSize() {

return mHelper.getMaxTextSize();

}


/**

    * Set the maximum text size to the given value, interpreted as "scaled pixel" units. This size

    * is adjusted based on the current density and user font size preference.

    *

    * @param size The scaled pixel size.

    *

    * @attr ref android.R.styleable#TextView_textSize

   */

public void setMaxTextSize(float size) {

mHelper.setMaxTextSize(size);

}


/**

    * Set the maximum text size to a given unit and value. See TypedValue for the possible

    * dimension units.

    *

    * @param unit The desired dimension unit.

    * @param size The desired size in the given units.

    *

    * @attr ref android.R.styleable#TextView_textSize

   */

public void setMaxTextSize(int unit, float size) {

mHelper.setMaxTextSize(unit, size);

}


/**

    * Returns the minimum size (in pixels) of the text in this View.

   */

public float getMinTextSize() {

return mHelper.getMinTextSize();

}


/**

    * Set the minimum text size to the given value, interpreted as "scaled pixel" units. This size

    * is adjusted based on the current density and user font size preference.

    *

    * @param minSize The scaled pixel size.

    *

    * @attr ref me.grantland.R.styleable#AutofitTextView_minTextSize

   */

public void setMinTextSize(int minSize) {

mHelper.setMinTextSize(TypedValue.COMPLEX_UNIT_SP, minSize);

}


/**

    * Set the minimum text size to a given unit and value. See TypedValue for the possible

    * dimension units.

    *

    * @param unit The desired dimension unit.

    * @param minSize The desired size in the given units.

    *

    * @attr ref me.grantland.R.styleable#AutofitTextView_minTextSize

   */

public void setMinTextSize(int unit, float minSize) {

mHelper.setMinTextSize(unit, minSize);

}


/**

    * Returns the amount of precision used to calculate the correct text size to fit within its

    * bounds.

   */

public float getPrecision() {

return mHelper.getPrecision();

}


/**

    * Set the amount of precision used to calculate the correct text size to fit within its

    * bounds. Lower precision is more precise and takes more time.

    *

    * @param precision The amount of precision.

   */

public void setPrecision(float precision) {

mHelper.setPrecision(precision);

}


@Override

public void onTextSizeChange(float textSize, float oldTextSize) {

// do nothing

}

}

[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: