Making TextView scrollable on Android
You don't need to use a ScrollView
actually.
Just set the
android:scrollbars = "vertical"
properties of your TextView
in your layout's xml file.
Then use:
yourTextView.setMovementMethod(new ScrollingMovementMethod());
in your code.
Bingo, it scrolls!
This is how I did it purely in XML:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ScrollView android:id="@+id/SCROLLER_ID" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbars="vertical" android:fillViewport="true"> <TextView android:id="@+id/TEXT_STATUS_ID" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0"/> </ScrollView></LinearLayout>
NOTES:
android:fillViewport="true"
combined withandroid:layout_weight="1.0"
will make the textview take up all available space.When defining the Scrollview, DO NOT specify
android:layout_height="fill_parent"
otherwise the scrollview doesn't work! (this has caused me to waste an hour just now! FFS).
PRO TIP:
To programmatically scroll to the bottom after appending text, use this:
mTextStatus = (TextView) findViewById(R.id.TEXT_STATUS_ID);mScrollView = (ScrollView) findViewById(R.id.SCROLLER_ID);private void scrollToBottom(){ mScrollView.post(new Runnable() { public void run() { mScrollView.smoothScrollTo(0, mTextStatus.getBottom()); } });}
All that is really necessary is the setMovementMethod(). Here's an example using a LinearLayout.
File main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextView android:id="@+id/tv1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello" /></LinearLayout>
File WordExtractTest.java
public class WordExtractTest extends Activity { TextView tv1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv1 = (TextView)findViewById(R.id.tv1); loadDoc(); } private void loadDoc() { String s = ""; for(int x=0; x<=100; x++) { s += "Line: " + String.valueOf(x) + "\n"; } tv1.setMovementMethod(new ScrollingMovementMethod()); tv1.setText(s); }}