Friday, June 24, 2011

How to calculate lsitview's total element's height

Sometimes we would be interested in finding height of the listview including all the child's height.(including the child which are not visible )

Usually the api listview.getChildCount() returns the count of number of elements which can be seen in the listview's height. But what i am insisting now is finding the height of all the childs of listview a collective height.

we will see how can we find the collective height of all child.

- Get the adapter instance from the listview.
- Get the count of adapter.
- And use adapter's getView(int position,View view,ViewGroup parent) api to get the view instance of all child
elements.
- Then use the measure api of View to measure the height of the view as below. I used here UNSPECIFIED to find out how big the view is.
- This api measures the widht and height. And use the getMeasuredHeight() api to find
the Measured Height.

private int getTotalHeightofListView() {
ListAdapter mAdapter = listview.getAdapter();
int listviewElementsheight = 0;
for(int i =0;i View mView = mAdapter.getView(i, null, listview);
mView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
listviewElementsheight+= mView.getMeasuredHeight();
}
return listviewElementsheight;
}


For additional information on MeasureSpec, taken from
http://developer.android.com/reference/android/view/View.html

MeasureSpecs are used to push requirements down the tree from parent to child. A MeasureSpec can be in one of three modes:

UNSPECIFIED: This is used by a parent to determine the desired dimension of a child view. For example, a LinearLayout may call measure() on its child with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how tall the child view wants to be given a width of 240 pixels.
EXACTLY: This is used by the parent to impose an exact size on the child. The child must use this size, and guarantee that all of its descendants will fit within this size.
AT_MOST: This is used by the parent to impose a maximum size on the child. The child must gurantee that it and all of its descendants will fit within this size."


No comments:

Post a Comment