calculate the listView's height. - Android User Interface

Android examples for User Interface:ListView

Description

calculate the listView's height.

Demo Code


//package com.java2s;

import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Main {
    /**//from w  w  w. j a  v a 2 s. co  m
     * calculate the listView's height. if you want to use listView in a
     * scrollView, you need to set the listView's height manually
     * 
     * @param listView
     * @return
     */
    public static int getListViewHeight(ListView listView) {
        ListAdapter adapter;

        if (listView == null || (adapter = listView.getAdapter()) == null) {
            return -1;
        }

        int height = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View item = adapter.getView(i, null, listView);
            if (item instanceof ViewGroup) {
                item.setLayoutParams(new LayoutParams(
                        LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));
            }

            item.measure(0, 0);
            height += item.getMeasuredHeight();
        }
        height += (listView.getPaddingBottom() + listView.getPaddingTop());

        height += listView.getDividerHeight() * (adapter.getCount() - 1);

        return height;
    }
}

Related Tutorials