Scrollable TextView in Android

When designing a UI on Android, it is sometimes hard to know in advance the required number of lines for TextView objects if they are dynamically modified by the app.

Thankfully, it is extremely easy to configure the TextView object to implement scrollbars, and allow the user, with simple gestures, to scroll the up/down/sideways in the TextView. So here it goes!

To start with, you need to declare your TextView in your layout XML file:

<TextView
        android:id="@+id/textViewResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="5"
        android:scrollbars="vertical"/>"

The two parameters to look out for are:

  • maxLines: this is the number of lines on display at any given time in the TextView
  • scrollbars: the actual gesture that will be supported by the TextView (here, just up or down)

The last thing to do is to declare your TextView in your java class:

TextView results;
results = (TextView) findViewById(R.id.textViewResult);
//next line enables the scrolling, do not forget!
results.setMovementMethod(new ScrollingMovementMethod()); 

This last call to setMovementMethod is important. If forgotten, you will end up with a truncated TextView in which you can not scroll!

Whenever you now set your TextView value, only 5 lines at a time will be shown, with smooth scrolling to display the hidden lines!

6 Responses to “Scrollable TextView in Android”

  1. rohitdroid says:

    if parent layout set scrollable then textview is not scrolling..please solve this problem.

  2. Dean says:

    Much appriciated. This helped a lot. One of the most unfriendly features I meet so far in Android. Thank you once more :)

  3. What’s up, everything is going nicely here and ofcourse every one is sharing
    facts, that’s really good, keep up writing.

  4. Javier says:

    thank you very much! Very useful. It works perfect!

  5. Mike R says:

    Simple and it worked. Thank you!

  6. Italy Tours says:

    great post.Never knew this, thanks for letting me know.

Leave a Reply