在我的ListField中,我希望能夠接受任何給定的長字符串,並且能夠在屏幕寬度範圍內打包第一行,然後只留下剩餘的字符串和將其顯示在下面並省略其餘部分。現在,這是我用我的畫漆調用內檢測包裝內容:黑莓ListField文本包裝 - 只有兩行
int totalWidth = 0;
int charWidth = 0;
int lastIndex = 0;
int spaceIndex = 0;
int lineIndex = 0;
String firstLine = "";
String secondLine = "";
boolean isSecondLine = false;
for (int i = 0; i < longString.length(); i++){
charWidth = Font.getDefault().getAdvance(String.valueOf(longString.charAt(i)));
//System.out.println("char width: " + charWidth);
if(longString.charAt(i) == ' ')
spaceIndex = i;
if((charWidth + totalWidth) > (this.getWidth()-32)){
//g.drawText(longString.substring(lastIndex, spaceIndex), xpos, y +_padding, DrawStyle.LEFT, w - xpos);
lineIndex++;
System.out.println("current lines to draw: " + lineIndex);
/*if (lineIndex = 2){
int idx = i;
System.out.println("first line " + longString.substring(lastIndex, spaceIndex));
System.out.println("second line " + longString.substring(spaceIndex+1, longString.length()));
}*/
//firstLine = longString.substring(lastIndex, spaceIndex);
firstLine = longString.substring(0, spaceIndex);
//System.out.println("first new line: " +firstLine);
//isSecondLine=true;
//xpos = 0;
//y += Font.getDefault().getHeight();
i = spaceIndex + 1;
lastIndex = i;
System.out.println("Rest of string: " + longString.substring(lastIndex, longString.length()));
charWidth = 0;
totalWidth = 0;
}
totalWidth += charWidth;
System.out.println("total width: " + totalWidth);
//g.drawText(longString.substring(lastIndex, i+1), xpos, y + (_padding*3)+4, DrawStyle.ELLIPSIS, w - xpos);
//secondLine = longString.substring(lastIndex, i+1);
secondLine = longString.substring(lastIndex, longString.length());
//isSecondLine = true;
}
現在這樣做的實際包裝任何給定的字符串(假設y值了偉大的工作得到適當的抵消,而且只畫在字符串寬度之後的文本超出了屏幕寬度,以及之後的剩餘字符串),但是,每當我嘗試獲取前兩行時,如果超過兩個字符串,它總是返回字符串的最後兩行線。有沒有更好的方法來做這種事情,因爲我剛剛從創意中脫穎而出?
感謝您的幫助,到目前爲止,它不需要進行第二行字體預先檢查,因爲在嘗試補償省略號寬度之後,它在嘗試猜測字符長度時中斷。但是,我能夠在單獨的函數中使用與drawText調用相同的算法,並讓第二行省略號以進行調用。到目前爲止,感謝您的幫助,儘管我想知道您是否可以重新評估僅用於踢球的猜測計算。 – 2010-02-17 17:00:52