【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
我正在寻找一种调整TextView
包装文本大小的最佳方法,以使其适合其getHeight和getWidth范围。 我不仅在寻找一种包装文本的方法-我想确保它既可以包装也可以包装得足够小以完全适合屏幕显示。
我在StackOverflow上看到过一些需要自动调整大小的情况,但它们要么是带有黑客解决方案的非常特殊的情况,要么没有解决方案,要么涉及递归地TextView
直到其足够小(这会占用大量内存并迫使用户可以观看每次递归操作时逐步缩小的文本)。
但是我敢肯定,那里有人找到了一个不涉及我正在做的事情的好的解决方案:编写一些繁琐的例程来分析和测量文本,调整文本的大小,然后重复进行直到找到合适的小尺寸为止。
TextView
使用哪些例程来包装文本? 难道不能以某种方式用来预测文本是否足够小吗?
tl; dr :有没有一种最佳实践来自动调整TextView
的大小以适合它的getHeight和getWidth边界?
#1楼
我刚刚创建了以下方法(基于Chase的思想),如果您想将文本绘制到任何画布上,可能会有所帮助:
private static void drawText(Canvas canvas, int xStart, int yStart,
int xWidth, int yHeigth, String textToDisplay,
TextPaint paintToUse, float startTextSizeInPixels,
float stepSizeForTextSizeSteps) {
// Text view line spacing multiplier
float mSpacingMult = 1.0f;
// Text view additional line spacing
float mSpacingAdd = 0.0f;
StaticLayout l = null;
do {
paintToUse.setTextSize(startTextSizeInPixels);
startTextSizeInPixels -= stepSizeForTextSizeSteps;
l = new StaticLayout(textToDisplay, paintToUse, xWidth,
Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
} while (l.getHeight() > yHeigth);
int textCenterX = xStart + (xWidth / 2);
int textCenterY = (yHeigth - l.getHeight()) / 2;
canvas.save();
canvas.translate(textCenterX, textCenterY);
l.draw(canvas);
canvas.restore();
}
例如,可以在任何自定义视图的任何onDraw()方法中使用它。
#2楼
实际上,一种解决方案在Google的DialogTitle类中……尽管它不如公认的那样有效,但它简单得多且易于适应。
public class SingleLineTextView extends TextView {
public SingleLineTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setSingleLine();
setEllipsize(TruncateAt.END);
}
public SingleLineTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setSingleLine();
setEllipsize(TruncateAt.END);
}
public SingleLineTextView(Context context) {
super(context);
setSingleLine();
setEllipsize(TruncateAt.END);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final Layout layout = getLayout();
if (layout != null) {
final int lineCount = layout.getLineCount();
if (lineCount > 0) {
final int ellipsisCount = layout.getEllipsisCount(lineCount - 1);
if (ellipsisCount > 0) {
final float textSize = getTextSize();
// textSize is already expressed in pixels
setTextSize(TypedValue.COMPLEX_UNIT_PX, (textSize - 1));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
}
}
#3楼
我从Chase的解决方案开始,但在设备(Galaxy Nexus,Android 4.1)上按预期工作之前,不得不调整两件事:
使用TextPaint的副本进行布局测量TextView.getPaint()的文档指出应以只读方式使用它,因此我在两个使用Paint对象进行度量的地方都制作了副本:
// 1. in resizeText() if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height) { // Draw using a static layout // modified: use a copy of TextPaint for measuring TextPaint paint = new TextPaint(textPaint); // 2. in getTextHeight() private int getTextHeight(CharSequence source, TextPaint originalPaint, int width, float textSize) { // modified: make a copy of the original TextPaint object for measuring // (apparently the object gets modified while measuring, see also the // docs for TextView.getPaint() (which states to access it read-only) TextPaint paint = new TextPaint(originalPaint); // Update the text paint object paint.setTextSize(textSize); ...
添加单位以设置文本大小
// modified: setting text size via this.setTextSize (instead of textPaint.setTextSize(targetTextSize)) setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize); setLineSpacing(mSpacingAdd, mSpacingMult);
有了这两个修改,该解决方案对我来说是完美的,谢谢蔡斯! 我不知道是否由于Android 4.x导致原始解决方案无法正常工作。 如果您想查看它的实际效果或测试它是否确实在您的设备上运行,可以查看我的抽认卡应用Flashcards ToGo ,在其中我可以使用此解决方案缩放抽认卡的文本。 文本可以具有任意长度,并且抽认卡可以在不同的活动中显示,有时更小有时更大,并且以横向+纵向模式显示,而且我还没有找到解决方案无法正常使用的特殊情况...
#4楼
Android 4.x的解决方法:
我找到了AutoResizeTextView,它在我的Android 2.1模拟器上很好用。 我太喜欢它了。 但是不幸的是,它在我自己的4.0.4手机和4.1仿真器上失败了。 尝试后,我发现可以通过在xml的AutoResizeTextView类中添加以下属性来轻松解决该问题:
android:ellipsize =“ none”
android:singleLine =“ true”
有了上面的2行,现在AutoResizeTextView可以在我的2.1和4.1仿真器以及我自己的4.0.4手机上完美运行。
希望这对您有所帮助。 :-)
#5楼
我的实现有点复杂,但具有以下优点:
- 考虑可用宽度和可用高度
- 适用于单行和多行标签
- 如果省略最小字体,则使用省略号
- 由于内部文本表示已更改,因此可以将原始设置的文本记住在单独的变量中
- 确保画布始终仅使用所需的大小,同时使用父级的所有可用高度
/**
* Text view that auto adjusts text size to fit within the view. If the text
* size equals the minimum text size and still does not fit, append with an
* ellipsis.
*
* Based on the original work from Chase Colburn
* <http://stackoverflow.com/a/5535672/305532>
*
* @author Thomas Keller <me@thomaskeller.biz>
*/
public class AutoResizeTextView extends TextView {
// in dip
private static final int MIN_TEXT_SIZE = 20;
private static final boolean SHRINK_TEXT_SIZE = true;
private static final char ELLIPSIS = '\u2026';
private static final float LINE_SPACING_MULTIPLIER_MULTILINE = 0.8f;
private static final float LINE_SPACING_MULTIPLIER_SINGLELINE = 1f;
private static final float LINE_SPACING_EXTRA = 0.0f;
private CharSequence mOriginalText;
// temporary upper bounds on the starting text size
private float mMaxTextSize;
// lower bounds for text size
private float mMinTextSize;
// determines whether we're currently in the process of measuring ourselves,
// so we do not enter onMeasure recursively
private boolean mInMeasure = false;
// if the text size should be shrinked or if the text size should be kept
// constant and only characters should be removed to hit the boundaries
private boolean mShrinkTextSize;
public AutoResizeTextView(Context context) {
this(context, null);
init(context, null);
}
public AutoResizeTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
init(context, attrs);
}
public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
// the current text size is used as maximum text size we can apply to
// our widget
mMaxTextSize = getTextSize();
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AutoResizeTextView);
mMinTextSize = a.getFloat(R.styleable.AutoResizeTextView_minFontSize, MIN_TEXT_SIZE);
mShrinkTextSize = a.getBoolean(R.styleable.AutoResizeTextView_shrinkTextSize, SHRINK_TEXT_SIZE);
a.recycle();
}
}
@Override
public void setTextSize(float size) {
mMaxTextSize = size;
super.setTextSize(size);
}
/**
* Returns the original, unmodified text of this widget
*
* @return
*/
public CharSequence getOriginalText() {
// text has not been resized yet
if (mOriginalText == null) {
return getText();
}
return mOriginalText;
}
@Override
public void setText(CharSequence text, BufferType type) {
if (!mInMeasure) {
mOriginalText = text.toString();
}
super.setText(text, type);
}
@SuppressLint("DrawAllocation")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mInMeasure = true;
try {
int availableWidth = MeasureSpec.getSize(widthMeasureSpec) - getCompoundPaddingLeft()
- getCompoundPaddingRight();
int availableHeight = MeasureSpec.getSize(heightMeasureSpec) - getCompoundPaddingTop()
- getCompoundPaddingBottom();
// Do not resize if the view does not have dimensions or there is no
// text
if (mOriginalText == null || mOriginalText.length() == 0 || availableWidth <= 0) {
return;
}
TextPaint textPaint = getPaint();
// start with the recorded max text size
float targetTextSize = mMaxTextSize;
String originalText = mOriginalText.toString();
String finalText = originalText;
Rect textSize = getTextSize(originalText, textPaint, targetTextSize);
boolean textExceedsBounds = textSize.height() > availableHeight || textSize.width() > availableWidth;
if (mShrinkTextSize && textExceedsBounds) {
// check whether all lines can be rendered in the available
// width / height without violating the bounds of the parent and
// without using a text size that is smaller than the minimum
// text size
float heightMultiplier = availableHeight / (float) textSize.height();
float widthMultiplier = availableWidth / (float) textSize.width();
float multiplier = Math.min(heightMultiplier, widthMultiplier);
targetTextSize = Math.max(targetTextSize * multiplier, mMinTextSize);
// measure again
textSize = getTextSize(finalText, textPaint, targetTextSize);
}
// we cannot shrink the height further when we hit the available
// height, but we can shrink the width by applying an ellipsis on
// each line
if (textSize.width() > availableWidth) {
StringBuilder modifiedText = new StringBuilder();
String lines[] = originalText.split(System.getProperty("line.separator"));
for (int i = 0; i < lines.length; i++) {
modifiedText.append(resizeLine(textPaint, lines[i], availableWidth));
// add the separator back to all but the last processed line
if (i != lines.length - 1) {
modifiedText.append(System.getProperty("line.separator"));
}
}
finalText = modifiedText.toString();
// measure again
textSize = getTextSize(finalText, textPaint, targetTextSize);
}
textPaint.setTextSize(targetTextSize);
boolean isMultiline = finalText.indexOf('\n') > -1;
// do not include extra font padding (for accents, ...) for
// multiline texts, this will prevent proper placement with
// Gravity.CENTER_VERTICAL
if (isMultiline) {
setLineSpacing(LINE_SPACING_EXTRA, LINE_SPACING_MULTIPLIER_MULTILINE);
setIncludeFontPadding(false);
} else {
setLineSpacing(LINE_SPACING_EXTRA, LINE_SPACING_MULTIPLIER_SINGLELINE);
setIncludeFontPadding(true);
}
// according to
// <http://code.google.com/p/android/issues/detail?id=22493>
// we have to add a unicode character to trigger the text centering
// in ICS. this particular character is known as "zero-width" and
// does no harm.
setText(finalText + "\u200B");
int measuredWidth = textSize.width() + getCompoundPaddingLeft() + getCompoundPaddingRight();
int measuredHeight = textSize.height() + getCompoundPaddingTop() + getCompoundPaddingBottom();
// expand the view to the parent's height in case it is smaller or
// to the minimum height that has been set
// FIXME: honor the vertical measure mode (EXACTLY vs AT_MOST) here
// somehow
measuredHeight = Math.max(measuredHeight, MeasureSpec.getSize(heightMeasureSpec));
setMeasuredDimension(measuredWidth, measuredHeight);
} finally {
mInMeasure = false;
}
}
private Rect getTextSize(String text, TextPaint textPaint, float textSize) {
textPaint.setTextSize(textSize);
// StaticLayout depends on a given width in which it should lay out the
// text (and optionally also split into separate lines).
// Therefor we calculate the current text width manually and start with
// a fake (read: maxmimum) width for the height calculation.
// We do _not_ use layout.getLineWidth() here since this returns
// slightly smaller numbers and therefor would lead to exceeded text box
// drawing.
StaticLayout layout = new StaticLayout(text, textPaint, Integer.MAX_VALUE, Alignment.ALIGN_NORMAL, 1f, 0f, true);
int textWidth = 0;
String lines[] = text.split(System.getProperty("line.separator"));
for (int i = 0; i < lines.length; ++i) {
textWidth = Math.max(textWidth, measureTextWidth(textPaint, lines[i]));
}
return new Rect(0, 0, textWidth, layout.getHeight());
}
private String resizeLine(TextPaint textPaint, String line, int availableWidth) {
checkArgument(line != null && line.length() > 0, "expected non-empty string");
int textWidth = measureTextWidth(textPaint, line);
int lastDeletePos = -1;
StringBuilder builder = new StringBuilder(line);
while (textWidth > availableWidth && builder.length() > 0) {
lastDeletePos = builder.length() / 2;
builder.deleteCharAt(builder.length() / 2);
// don't forget to measure the ellipsis character as well; it
// doesn't matter where it is located in the line, it just has to be
// there, since there are no (known) ligatures that use this glyph
String textToMeasure = builder.toString() + ELLIPSIS;
textWidth = measureTextWidth(textPaint, textToMeasure);
}
if (lastDeletePos > -1) {
builder.insert(lastDeletePos, ELLIPSIS);
}
return builder.toString();
}
// there are several methods in Android to determine the text width, namely
// getBounds() and measureText().
// The latter works for us the best as it gives us the best / nearest
// results without that our text canvas needs to wrap its text later on
// again.
private int measureTextWidth(TextPaint textPaint, String line) {
return Math.round(textPaint.measureText(line));
}
}
[2012年11月21日修订]
- 修复了省略号的位置(错误一处)
- 重做的文字大小计算; 现在总是测量包括换行符在内的全文,以解决以下问题:当两个单条被测行的高度相加后得出的结果与整个文本的高度测量结果不一致
- 无需循环查找最小的可用文本大小,只需在第一次测量后进行计算即可
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3144629