set GridView Width - Android User Interface

Android examples for User Interface:GridView

Description

set GridView Width

Demo Code


//package com.java2s;
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;
        }//ww  w.  j av  a2  s  .co m
        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