Android scrollable TextView

Screens of many Android devices are small. Typically you have limited space on the screens to display large amount of text. However, this problem can be solved by making the text container scrollable. In this tip, I am going to show how to make a TextView scrollable so that you will be able to scroll to see the rest of text when you have large amount of text in TextView.

Now you to have a workable example application, you will create a new Android project. Then add a TextView to the activity_main.xml file as shown below. To display a scrollbar when you scroll the TextView, you need to use the android:scrollbars in the layout file. In the layout file, the height of 150sp is set to the TextView. If the text cannot fit to the TextView in this height, a vertical scrollbar will display.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >
  
  <TextView
   android:id="@+id/txt_view"
   android:layout_width="match_parent"
   android:layout_height="150sp"
   android:gravity="top"
   android:textSize="40sp"
   android:scrollbars="vertical"
   />
  
  
</LinearLayout>
  

To make the TextView scrollable, you will call the setMovementMethod of the TextView instance. The method accepts an instance of the ScrollingMovementMethod class. In the onStart method of the MainActivity class, you write code to display text in the TextView and make it scrollable.

public void onStart(){
   super.onStart();
   TextView txtview=(TextView)findViewById(R.id.txt_view);
   String text="I like programming in Android. This tip shows you how to make a TextView scrollable in Android.";
   txtview.setText(text);
   txtview.setMovementMethod(new ScrollingMovementMethod());
  
  
   }

Android-scrollable-TextView

Posted by: Dara | post date: 06-20-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.