ant*_*tsu 6 android word-wrap textview
这个问题可能是一样的这一个,但因为没有它的答案真正解决问题,我再问一遍.
我的应用程序有一个TextView,偶尔会显示很长的URL.出于美观原因(并且由于URL不包含空格),理想的行为是在跳到下一行之前完全填充每一行,如下所示:
|http://www.domain.com/som|
|ething/otherthing/foobar/|
|helloworld |
Run Code Online (Sandbox Code Playgroud)
相反,会在URL附近破坏URL,就好像它们是空格一样.
|http://www.domain.com/ |
|something/otherthing/ |
|foobar/helloworld |
Run Code Online (Sandbox Code Playgroud)
我尝试扩展TextView类并添加一个breakManually方法的修改版本(在这里找到)来欺骗TextView并做我需要的东西,在onSizeChanged(覆盖)上调用它.除了TextView在ListView中之外,它工作正常.当滚动隐藏此自定义TextView并将其恢复时,其内容将返回到原始中断行为,因为在不调用onSizeChanged的情况下重新绘制视图.
通过在onDraw中调用breakManually,我能够解决这个问题.这在任何时候都呈现出预期的行为,但是性能成本很高:因为只要滚动ListView并且breakManually方法不是"轻量级" 就会调用onDraw,即使在高端四边形上,滚动也会出现难以接受的延迟 - 核心设备.
下一步是爬行TextView源代码,试图找出它在何处以及如何分割文本,并希望覆盖它.这完全失败了.我(一个新手)花了一整天的时间毫无结果地看着我大多无法理解的代码.
这就把我带到了这里.有人可以指出我应该覆盖的正确方向(假设它是可能的)?或者也许有一种更简单的方式来实现我想要的东西?
这是我提到的breakManually方法.由于使用了getWidth(),它仅在测量视图后调用时才有效.
private CharSequence breakManually (CharSequence text) {
int width = getWidth() - getPaddingLeft() - getPaddingRight();
// Can't break with a width of 0.
if (width == 0) return text;
Editable editable = new SpannableStringBuilder(text);
//creates an array with the width of each character
float[] widths = new float[editable.length()];
Paint p = getPaint();
p.getTextWidths(editable.toString(), widths);
float currentWidth = 0.0f;
int position = 0;
int insertCount = 0;
int initialLength = editable.length();
while (position < initialLength) {
currentWidth += widths[position];
char curChar = editable.charAt(position + insertCount);
if (curChar == '\n') {
currentWidth = 0.0f;
} else if (currentWidth > width) {
editable.insert(position + insertCount , "\n");
insertCount++;
currentWidth = widths[position];
}
position++;
}
return editable.toString();
}
Run Code Online (Sandbox Code Playgroud)
对于那些烦恼阅读的人,谢谢你的时间.
小智 0
如果您不使用等宽字体,那么在某些情况下甚至无法很好地对齐它。由于 URL 中没有空格,因此类似 Justify 的对齐方式不太可能解决问题。我建议您对特定的 TextView 使用等宽字体。然后,确定每行的固定字符数,并"\n"在这些字符之后断开要显示的字符串。
这并没有回答你的问题,但我想这是最顺利的方式。
| 归档时间: |
|
| 查看次数: |
812 次 |
| 最近记录: |