Java 如何将不自动适合libgdx标签的单词移动到下一行?
我有一个很长的句子。我应该使用标签以外的其他小部件吗? 当我将标签的文本设置为一个非常大的句子时,标签最大宽度后面的单词会被切碎 可能的黑客行为是在要移动到字符串中下一行的位置手动添加\n。但这不可能使这个过程自动化 这张图片中的标签很长,其文字如下- 我在花园里\我在花园里。我在花园里 如何将最后一个单词自动移动到同一标签中的第三行Java 如何将不自动适合libgdx标签的单词移动到下一行?,java,android,libgdx,Java,Android,Libgdx,我有一个很长的句子。我应该使用标签以外的其他小部件吗? 当我将标签的文本设置为一个非常大的句子时,标签最大宽度后面的单词会被切碎 可能的黑客行为是在要移动到字符串中下一行的位置手动添加\n。但这不可能使这个过程自动化 这张图片中的标签很长,其文字如下- 我在花园里\我在花园里。我在花园里 如何将最后一个单词自动移动到同一标签中的第三行 您可以计算文本视图的宽度。只需textview.getWidth,通过以下方法计算实际文本的宽度: Paint p = new Paint(); p.measur
您可以计算文本视图的宽度。只需textview.getWidth,通过以下方法计算实际文本的宽度:
Paint p = new Paint();
p.measureText("your text here");
并一起比较,如果实际文本宽度大于textview宽度,请添加\n
更新:
在您的例子中,不计算整个实际文本,只需逐个字符计算宽度,求和宽度并与textview宽度进行比较
工作完成了。希望这有帮助
String insertNewlineChars(String textToDisplay, Float maxLabelWidth, BitmapFont font)
{
float textWidth=0;
ArrayList<String> words = new ArrayList<String>(Arrays.asList(textToDisplay.split(" ")));
String addWordsToSentence;
//add first word
String nextWord = words.get(0) ;
addWordsToSentence = nextWord + " ";
textWidth = font.getBounds(addWordsToSentence).width;
//add 2nd to last word
for(int i=1;i<words.size();i++)
{
nextWord = words.get(i);
textWidth += font.getBounds(nextWord).width;
//add word to a new line
if(textWidth > maxLabelWidth)
{
//push to next line
textWidth = font.getBounds(nextWord).width;
addWordsToSentence = addWordsToSentence.concat("\n" + nextWord + " ");
}
//add word to the same line
else
{
addWordsToSentence = addWordsToSentence.concat(nextWord + " ");
}
}
return addWordsToSentence;
}