ScrollView Layout

Web Hosting

This tutorial is to show how to use Vertical and Horizontal scrollviews in Android.

Below example uses a table with multiple rows, once the table exceeds the size of the screen, it automatically scrolls vertically or horizontally.
The below code shows how to build a Textview and TableLayout view with multiple rows dynamically.
scrollview
The following widgets need for building a scroll view
  • ScrollView
  • HorizontalScrollView
  • A TableLayout view with multiple rows added and
  • A TextView to display text inside the table rows.
  1. Create an Android Application Project.
  2. Go to /YOUR_PROJECT/res/layout/activity_main.xml and add a scrollview to xml as shown in below code.

    <ScrollView android:id="@+id/myscroll1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
    • First create a TableLayoutTableRow and Textview.
    • Then add TextView to TableRow , then add TableRow to TableLayout.
    • Finally add TableLayout to Scrollview defined in Step.2 .
  1. Add the following code in MainActivity.java.
    TableLayout tableLayout;
    ScrollView scrollView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    scrollView = (ScrollView)findViewById(R.id.myscroll1);
    tableLayout=new TableLayout(this);
    for(int i=1;i<50;i++) {
    TableRow tableRow=new TableRow(this);
    TextView text=new TextView(this);
    text.setId(i);
    text.setText(" WhiteSof Test: "+i);
    tableRow.addView(text);
    tableLayout.addView(tableRow);
    }
    scrollView.addView(tableLayout);
    }

  2. Horizontal scrollbars are added by using HorizontalScrollView as shown below.

    <ScrollView
            android:id="@+id/id_Scroll"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
     <HorizontalScrollView
                android:id="@+id/id_hScroll"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
                 <TableLayout 
                    android:id="@+id/id_mainTable"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                     
                 </TableLayout>
             </HorizontalScrollView>
    <ScrollView>

Web Hosting

No comments:

Post a Comment