Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

11. ScrollView

ScrollViews can be used to contain one view that might be to big to fit on one screen. If the view is to big the ScrollView will display a scroll bar to scroll the context. Of course this view can be a layout which can then contain other elements.

Create an android project "de.vogella.android.scrollview" with the activity "ScrollView". Create the following layout and class.

			
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent" android:fillViewport="true">

<LinearLayout android:id="@+id/LinearLayout01" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content">
	<TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a header" android:textAppearance="?android:attr/textAppearanceLarge" android:paddingLeft="8dip" android:paddingRight="8dip" android:paddingTop="8dip"></TextView>
	<TextView android:text="@+id/TextView02" android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1.0"></TextView>
	
	<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content">
		<Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Submit" android:layout_weight="1.0"></Button>
		<Button android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" android:layout_weight="1.0"></Button>
	</LinearLayout>
</LinearLayout>
</ScrollView>

		

			
package de.vogella.android.scrollview;

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

public class ScrollView extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView view =	(TextView) findViewById(R.id.TextView02);
        String s="";
        for (int i=0; i < 100; i++) {
        	s += "vogella.de ";
        }
        view.setText(s);
    }
}
		

The attribute "android:fillViewport="true"" ensures that the the scrollview is set to the full screen even if the elements are smaller then one screen and the "layout_weight" tell the android system that these elements should be extended.