scrolllist view in android code example

Example 1: scrollview android

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stretchColumns="1">

        <!-- everything you already have -->

    </TableLayout>
</ScrollView>

Example 2: list view in scrollview

//This method needs to be run each time the list view data changes
//It sets the height to the height of all the individual views

public static void setListViewHeightBasedOnChildren
                                              (ListView listView) {ListAdapter listAdapter = listView.getAdapter();if (listAdapter == null) return;int desiredWidth = easureSpec.makeMeasureSpec(listView.getWidth(),
                                           MeasureSpec.UNSPECIFIED);int totalHeight = 0; 
  View view = null;for (int i = 0; i < listAdapter.getCount(); i++) { 
    view = listAdapter.getView(i, view, listView);if (i == 0) view.setLayoutParams(new   
                                ViewGroup.LayoutParams(desiredWidth, 
                                        LayoutParams.WRAP_CONTENT));
   
    view.measure(desiredWidth, MeasureSpec.UNSPECIFIED); 
    totalHeight += view.getMeasuredHeight(); 
  }
 
  ViewGroup.LayoutParams params = listView.getLayoutParams();   
   
  params.height = totalHeight + (listView.getDividerHeight() * 
                                     (listAdapter.getCount() — 1));  
   
  listView.setLayoutParams(params); 
  listView.requestLayout(); 
}                                            (ListView listView) {ListAdapter listAdapter = listView.getAdapter();if (listAdapter == null) return;int desiredWidth = easureSpec.makeMeasureSpec(listView.getWidth(),                                           MeasureSpec.UNSPECIFIED);int totalHeight = 0;   View view = null;for (int i = 0; i < listAdapter.getCount(); i++) {     view = listAdapter.getView(i, view, listView);if (i == 0) view.setLayoutParams(new                                   ViewGroup.LayoutParams(desiredWidth,                                         LayoutParams.WRAP_CONTENT));       view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);     totalHeight += view.getMeasuredHeight();   }   ViewGroup.LayoutParams params = listView.getLayoutParams();        params.height = totalHeight + (listView.getDividerHeight() *                                      (listAdapter.getCount() — 1));       listView.setLayoutParams(params);   listView.requestLayout(); }

Tags:

Misc Example