Make text fit exactly as the screen size

2019-05-10 10:34发布

问题:

I have a long text so I've decided to divide it into pages, and I put a so each swipe scrolls to the next page.. The way I did it was:

    NumberOfPages=text.length()/CharPerPage;    //CharPerPage=500;  
    NumberOfPages++;        

    Chapters.add(text.indexOf(" ", CurrentPage*CharPerPage));
    CurrentPage++;
    int tmp=0;
    for(int i =NumberOfPages;i>0;i--)
    {           
         tmp =(CurrentPage*CharPerPage);
        if(tmp>text.length())
        {
            Chapters.add(text.length());    
            break;
        }
        else
        {
        Chapters.add(text.indexOf(" ", tmp));   
        CurrentPage++;
        }
    }

So I divide the text into pages, and each page has 500 chars... But this isnt good since Android has different screen sizes and shapes, and line breaks arent counted so it may go beyond the screen... So can anyone suggest a way to know how many chars are needed to fill the screen so i can make the rest of the text to another page? Thanks.

回答1:

Ok here is a shot - and a rather clumsy one but in short:

*You need need to know if any give line of text will fit width-wise in your view *You need to know how many lines you have *You need to handle embedded newlines

so

will some text fit on any given line

  private boolean isTooLarge (TextView text, String newText) {    
     float textWidth = text.getPaint().measureText(newText);
     return (textWidth >= text.getMeasuredWidth ());
  } 

how many lines does your textview have:

numLinesPerPage=mTextView.getHeight()/mTextView.getLineHeight();  //not this doesn't handle special cases where you've changed the font, bolded it etc

With these two tools you could iterate through your text adding words keeping track of how many lines you have left to work with (and handle your newlines if your text contains them)

note: getHeight can't be called in constructor since it doesn't know the height yet - you could also do this in onDraw or maybe onMeasure if you have a custom control.