Blackberry ListField Text Wrapping - only two lines.

Posted by Diego Tori on Stack Overflow See other posts from Stack Overflow or by Diego Tori
Published on 2010-02-02T20:04:28Z Indexed on 2010/05/09 18:48 UTC
Read the original article Hit count: 286

Filed under:
|
|
|
|

Within my ListField, I want to be able to take any given long String, and just be able to wrap the first line within the width of the screen, and just take the remaining string and display it below and ellipsis the rest. Right now, this is what I'm using to detect wrapping within my draw paint call:

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;
}

Now this does a great job of actually wrapping any given string (assuming the y values were properly offsetted and it only drew the text after the string width exceeded the screen width, as well as the remaining string afterwards), however, every time I try to get the first two lines, it always ends up returning the last two lines of the string if it goes beyond two lines. Is there a better way to do this sort of thing, since I am fresh out of ideas?

© Stack Overflow or respective owner

Related posts about blackberry

Related posts about text