有很多选择。
一种是用“+”分隔:
canvas.drawText("Style.FILL.show the full complete text Thanks dude.."+
"I am searching for this thing since last three days. But no where"+
" they have given as simple as you given ", 75, 110, paint);
另一种是将字符串放入 strings.xml 中。这样您的代码中就没有“垃圾”,而且您可以添加限定符来确定何时使用每个字符串(例如本地化)。
编辑:我以为你的意思是它在代码中惹恼了你。现在我明白你需要它在应用程序本身中工作。
下一个代码将采用任何文本,并根据您给它的矩形使其具有自动换行。如果文本太长,即使指定的最大行数,文本也会被截断。它还支持文本对齐。
这是代码:
// TODO make this whole class more customizable (text size, text color,gravity...), maybe using textView
// TODO make this code better somehow. the positioning is very weird.
final Rect rect = ...;
// find the truncated text to show based on the max lines that are allowed:
StaticLayout sl;
int pivot, maxCharactersCount = mTextToShow.length(), minCharactersCount = 0;
sl = new StaticLayout(mTextToShow, mTextPaint, rect.width(), Alignment.ALIGN_NORMAL, 1, 1, false);
int lineCount = sl.getLineCount();
if (lineCount > mMaxLines)
while (true) {
pivot = (maxCharactersCount + minCharactersCount) / 2;
final String text = mTextToShow.substring(0, pivot);
sl = new StaticLayout(text, mTextPaint, rect.width(), Alignment.ALIGN_NORMAL, 1, 1, false);
lineCount = sl.getLineCount();
if (lineCount <= mMaxLines) {
minCharactersCount = pivot;
if (maxCharactersCount <= minCharactersCount + 1)
break;
} else
maxCharactersCount = pivot;
}
if (lineCount == 0)
return;
// get the bounding width of the text (of all lines):
int maxTextWidth = 0;
for (int i = 0; i < lineCount; ++i)
maxTextWidth = (int) Math.max(maxTextWidth, sl.getLineWidth(i));
// some initializations...
final float textHeight = mTextPaint.getTextSize();
final float totalTextHeight = textHeight * lineCount;
final float rotation = getRotation();
final String truncatedText = sl.getText().toString();
// calculate where to start the drawing:
final float yCenter = (rect.bottom + rect.top) / 2;
final float yStart = yCenter - totalTextHeight / 2;
int startX;
switch (mAlign) {
case CENTER:
startX = (rect.left + rect.right) / 2;
break;
case RIGHT:
startX = rect.right;
break;
case LEFT:
default:
startX = rect.left;
break;
}
// start drawing:
canvas.save();
if (rotation != 0)
canvas.rotate(rotation);
canvas.translate(startX, yStart);
// for each line, draw it in the corresponding location, based on its width and which line it is:
for (int i = 0; i < lineCount; ++i) {
final int lineTextWidth = (int) sl.getLineWidth(i);
final String lineText = truncatedText.substring(sl.getLineStart(i), sl.getLineEnd(i));
int xToDrawRelativeToStart = 0;
switch (mAlign) {
case CENTER:
xToDrawRelativeToStart = -lineTextWidth / 2;
break;
case RIGHT:
xToDrawRelativeToStart = -lineTextWidth;
break;
case LEFT:
default:
xToDrawRelativeToStart = 0;
break;
}
canvas.drawText(lineText, xToDrawRelativeToStart, textHeight * (i + 1), mTextPaint);
}
canvas.restore();