set GridView Height - Android android.widget

Android examples for android.widget:GridView

Description

set GridView Height

Demo Code

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;

public class Main {

  @SuppressLint("NewApi")
  public static void setGridViewHeight(Context context, GridView listView, int n) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
      return;//ww  w. j a  va  2s. c  om
    }
    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 = 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