set GridView Width - Android android.widget

Android examples for android.widget:GridView

Description

set GridView Width

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 setGridViewWidth(Context context, GridView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
      return;//from   w w w.j a  va  2s . c om
    }
    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
      View listItem = listAdapter.getView(i, null, listView);
      listItem.measure(0, 0);
      totalHeight += listItem.getMeasuredWidth();
    }
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.width = totalHeight + listView.getPaddingLeft() + listView.getPaddingRight();
    params.width += 5;// if without this statement,the listview will be a little short
    listView.setLayoutParams(params);
  }

}

Related Tutorials