set GridView Height - Android User Interface

Android examples for User Interface:GridView

Description

set GridView Height

Demo Code


import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Main{
    @SuppressLint("NewApi")
    public static void setGridViewHeight(Context context,
            GridView listView, int n) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }//from  w ww .  j ava  2 s  .  com
        int totalHeight = 0;
        for (int i = 0; i < (listAdapter.getCount() + n - 1) / n; i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        int spacing = ScreenUtils.dipToPx(context, 10);
        params.height = totalHeight + spacing
                * ((listAdapter.getCount() - 1) / n)
                + listView.getPaddingBottom() + listView.getPaddingTop();
        params.height += 5;//if without this statement,the listview will be a little short
        listView.setLayoutParams(params);
    }
}

Related Tutorials