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!