codeofaninja
website

How To Scroll Android TextView

Photo of Mike Dalisay
Modified Friday, July 22, 2011
by - @ninjazhai
Hi there! Today we're going to do a script that will make a scrolling Android TextView. I found this one useful when I'm testing my other code snippets. The situation is, my text output exceeds the height of my android device screen, I cannot see the whole output unless I make the TextView scrolling.

How To Scroll Android TextView
Let's rock and scroll! :))


We will have the following code on our main activity - ScrollingTextView.java

package com.example.ScrollingTextView;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ScrollingTextView extends Activity {
    TextView tv;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //textViewWithScroll is the name of our TextView on main.xml
        this.tv = (TextView) this.findViewById(R.id.textViewWithScroll);
        
        //initializing a blank textview
        //so that we can just append a text later
        tv.setText("");
        
        //display the text 10 times
        //so that it will exceed the device screen height
        //and be able to scroll
        for(int x = 1; x < 11; x++ ){
            tv.append("Hi there!\n");
            tv.append("Did you know that...\n");
            tv.append("I'm handsome? Hahaha! Just kidding.\n");
        }
    }
}

And then the following codes on our layout file - main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/ScrollView01"  
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    android:layout_below="@+id/DownloadData" >  
    
        <TextView  
        android:text="Text here..."
        android:id="@+id/textViewWithScroll" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"/>
        
    </ScrollView>  
    
</RelativeLayout>

We will have something like this on the output:

Click to enlarge.

For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
 
 
Fundamentals
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.