set GridView Height On Children - Android User Interface

Android examples for User Interface:GridView

Description

set GridView Height On Children

Demo Code


//package com.java2s;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;

public class Main {
    public static void setGridViewHeightOnChildren(GridView gridView) {
        ListAdapter adapter = gridView.getAdapter();

        if (adapter == null) {
            // pre-condition
            return;
        }/*  w  w w  .ja  v  a  2  s . c om*/
        int rowCount = 0;
        int numColimns = gridView.getNumColumns();
        if (numColimns == -1) {
            numColimns = 2;
        }

        float numLine = adapter.getCount() / numColimns;
        int numLineInt = adapter.getCount() / numColimns;

        if (numLine - (float) numLineInt < 1.0) {
            rowCount = numLineInt + 1;
        } else if (numLine - (float) numLineInt == 0.0) {
            //  
            rowCount = numLineInt;
        }

        int totalHeight = 0;
        for (int i = 0; i < rowCount; i++) {
            View listItem = adapter.getView(i, null, gridView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.height = totalHeight
                + (gridView.getVerticalSpacing() * (rowCount - 1));
        gridView.setLayoutParams(params);

    }
}

Related Tutorials