在 2 行上显示文本视图(任意字符串长度)

我有一个字符串数组如下:[“你好”,“说再见”,“我是开发人员”,“Java是一种面向对象的语言”,“Web应用程序编程,...]

如果字符串超过一个单词,我想在 TextView 上显示两行,并且两行之间的字符数差异最小。

例如:“Web应用程序编程”应该是“Web应用程序编程”,而不是“Web应用程序编程”。

有什么办法可以做到这一点吗?


qq_花开花谢_0
浏览 84回答 1
1回答

繁星淼淼

这应该适合您的问题:private String wrapText(String in) {&nbsp; &nbsp; String r;&nbsp; &nbsp; if(in.contains(" ")) {&nbsp; &nbsp; &nbsp; &nbsp; int middle = in.length() / 2;&nbsp; &nbsp; &nbsp; &nbsp; int before = getSpaceBeforeIndex(in, middle);&nbsp; &nbsp; &nbsp; &nbsp; int after = getSpaceAfterIndex(in, middle);&nbsp; &nbsp; &nbsp; &nbsp; int rightOne;&nbsp; &nbsp; &nbsp; &nbsp; if(before == -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rightOne = after;&nbsp; &nbsp; &nbsp; &nbsp; } else if(after == -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rightOne = before;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rightOne = (middle - before) < (after - middle)? before : after;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; r = in.substring(0, rightOne) + "\n" + in.substring(rightOne);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; r = in;&nbsp; &nbsp; }&nbsp; &nbsp; return r;}private static int getSpaceBeforeIndex(String in, int index) {&nbsp; &nbsp; String cut = in.substring(0, index);&nbsp; &nbsp; int firstSpace = cut.lastIndexOf(" ");&nbsp; &nbsp; return firstSpace;}private static int getSpaceAfterIndex(String in, int index) {&nbsp; &nbsp; int nextSpace = in.indexOf(" ", index);&nbsp; &nbsp; return nextSpace;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java