Mat*_*inn 8 android word-wrap textview
有没有办法控制TextView选择包装文本的位置?我遇到的问题是它想要在句点换行 - 所以像"在美国和加拿大可用"之类的字符串可以在U和S之间的时段之后换行.是否有办法告诉TextView不要除非有一个句号和一个空格,或者一些程序化的方法来控制包装,否则包装?
Mat*_*inn 14
我最终编写了自己的算法,只在空格上打破文本.我最初使用了Paint的breakText方法,但是遇到了一些问题(实际上可以在这个版本的代码中解决,但是没关系).这不是我最好的代码块,它肯定可以清理一下,但它可以工作.由于我重写了TextView,我只是从onSizeChanged方法调用它来确保有一个有效的宽度.
private static void breakManually(TextView tv, Editable editable)
{
int width = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight();
if(width == 0)
{
// Can't break with a width of 0.
return false;
}
Paint p = tv.getPaint();
float[] widths = new float[editable.length()];
p.getTextWidths(editable.toString(), widths);
float curWidth = 0.0f;
int lastWSPos = -1;
int strPos = 0;
final char newLine = '\n';
final String newLineStr = "\n";
boolean reset = false;
int insertCount = 0;
//Traverse the string from the start position, adding each character's
//width to the total until:
//* A whitespace character is found. In this case, mark the whitespace
//position. If the width goes over the max, this is where the newline
//will be inserted.
//* A newline character is found. This resets the curWidth counter.
//* curWidth > width. Replace the whitespace with a newline and reset
//the counter.
while(strPos < editable.length())
{
curWidth += widths[strPos];
char curChar = editable.charAt(strPos);
if(((int) curChar) == ((int) newLine))
{
reset = true;
}
else if(Character.isWhitespace(curChar))
{
lastWSPos = strPos;
}
else if(curWidth > width && lastWSPos >= 0)
{
editable.replace(lastWSPos, lastWSPos + 1, newLineStr);
insertCount++;
strPos = lastWSPos;
lastWSPos = -1;
reset = true;
}
if(reset)
{
curWidth = 0.0f;
reset = false;
}
strPos++;
}
if(insertCount != 0)
{
tv.setText(editable);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3448 次 |
| 最近记录: |