get GridView Column Width via reflection - Android User Interface

Android examples for User Interface:GridView

Description

get GridView Column Width via reflection

Demo Code


//package com.java2s;
import java.lang.reflect.Field;
import android.annotation.SuppressLint;

import android.os.Build;

import android.widget.GridView;

public class Main {
    @SuppressLint("NewApi")
    public static int getColumnWidth(final GridView gridView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            return gridView.getColumnWidth();
        } else {// w w  w . j  a  va2  s  .  c  o m
            try {
                Field field = GridView.class
                        .getDeclaredField("mColumnWidth");
                field.setAccessible(true);
                Integer value = (Integer) field.get(gridView);
                field.setAccessible(false);

                return value.intValue();
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

Related Tutorials