Set GridView's height via ViewGroup.LayoutParams - Android User Interface

Android examples for User Interface:GridView

Description

Set GridView's height via ViewGroup.LayoutParams

Demo Code

/*//from  www .j av a  2s  . c om
 * Copyright (C) 2016 venshine.cn@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import android.view.View;
import android.view.ViewGroup;

import android.widget.GridView;
import android.widget.ListAdapter;

import java.lang.reflect.Field;

public class Main {
    /**
     * Set GridView's height
     *
     * @param GridView
     */
    public static void setGridViewHeight(GridView GridView) {
        int h = getGridViewHeight(GridView);
        if (h == 0 || GridView == null) {
            return;
        }
        ViewGroup.LayoutParams params = GridView.getLayoutParams();
        params.height = h;
        GridView.setLayoutParams(params);
    }

    /**
     * Get GridView's height
     *
     * @param GridView
     * @return
     */
    public static int getGridViewHeight(GridView GridView) {
        if (GridView == null) {
            return 0;
        }
        ListAdapter listAdapter = GridView.getAdapter();
        if (listAdapter == null) {
            return 0;
        }
        int rows = 0;
        int columns = GridView.getNumColumns();
        int horizontalBorderHeight = getGridViewRequestHorizontalSpacing(GridView);
        if (listAdapter.getCount() % columns > 0) {
            rows = listAdapter.getCount() / columns + 1;
        } else {
            rows = listAdapter.getCount() / columns;
        }
        int totalHeight = 0;
        for (int i = 0; i < rows; i++) {
            View listItem = listAdapter.getView(i, null, GridView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        return (totalHeight + horizontalBorderHeight * (rows - 1));
    }

    /**
     * Get GridView's request horizontal spacing
     *
     * @param GridView
     * @return
     */
    private static int getGridViewRequestHorizontalSpacing(GridView GridView) {
        int spacing = 0;
        Field field = null;
        try {
            field = GridView.getClass().getDeclaredField(
                    "mRequestedHorizontalSpacing");
            field.setAccessible(true);
            spacing = field.getInt(GridView);
        } catch (Exception e) {
        }
        return spacing;
    }
}

Related Tutorials