VSB VSB - 1 year ago 115
Android Question

last word displayed in a textview

I'm going to display a complete text document on several pages in an android app. Each page contains a TextView control which is in charge to display text. It also contains a next button, which is in charge to update textview and follow the text just from where it ended in last displayed section.

The problem is how can i find the last displayed word in displayable area of TextView?

Note: In this app, textView is not supposed to be scrolled or use ellipsize.
It also must be noted textsize can be increased or decreased.
To understand the situation better:
Sample Text to be displayed:

This is whole text. At first Page It just ended here and must be
followed from here.

And this is the sample illustration of the its display. The question is how to find word "here" as last word displayed in page 1?
And this is the sample illustration of the its display. The question is how to find word "here" as last word displayed in page 1?

Answer Source

Finally I developed piece of code which can find last displayed word. Considering that we are going to use a text view with properties width and height as its size and textSize in dp as size of text, function formatStringToFitInTextView evaluates the last displayed word in the textview and returns it to as function output. In below sample we considered SERIF font as TextView typeface.

String formatStringToFitInTextView(int width, int heigth, String inputText,float textSize) {
    String[] words;
    String lastWord = "";
    String finalString="";
    StaticLayout stLayout;
    int i,numberOfWords;
    int h;
    Typeface tf = Typeface.SERIF;
    TextPaint tp = new TextPaint();
    tp.setTypeface(tf );
    tp.setTextSize(textSize);   //COMPLEX_UNIT_DP

    words = inputText.split(" ");   //split input text to words
    numberOfWords = words.length;
    for (i=0;i<numberOfWords;i++){ 
        stLayout= measure(tp,finalString+words[i]+" ",width);
        if (stLayout.getHeight() > heigth) break;
        finalString += words[i]+" ";
        lastWord  = words[i];

    return lastWord;
StaticLayout measure( TextPaint textPaint, String text, Integer wrapWidth ) {
    int boundedWidth = Integer.MAX_VALUE;
    if( wrapWidth != null && wrapWidth > 0 ) {
      boundedWidth = wrapWidth;
    StaticLayout layout = new StaticLayout( text, textPaint, boundedWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false );
    return layout;

The total logic to do actions is split the input text into words and add words one by one to textview till it fills up the provided height and width and then return the last added word as last displayed word.

Note: Thanks to Moritz, I used function measure from this answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download