get GridView Column Width Compatible - Android User Interface

Android examples for User Interface:GridView

Description

get GridView Column Width Compatible

Demo Code


//package com.java2s;
import android.annotation.TargetApi;
import android.os.Build;
import android.widget.GridView;
import java.lang.reflect.Field;

public class Main {
    @TargetApi(16)/*w ww  .  j ava 2  s  . c o m*/
    // since we conditionally check for API method availability
    public static int getGridViewColumnWidthCompatible(
            final GridView gridView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            return gridView.getColumnWidth();
        } else {
            Field columnWidthField = null;
            try {
                columnWidthField = GridView.class
                        .getDeclaredField("mColumnWidth");
                columnWidthField.setAccessible(true);

                return (Integer) columnWidthField.get(gridView);
            } catch (final NoSuchFieldException noSuchFieldException) {
                throw new RuntimeException(
                        "No column width field, this is unexpected",
                        noSuchFieldException);
            } catch (final IllegalAccessException illegalAccessException) {
                throw new RuntimeException(
                        "Field wasn't accessible while it should have been made so, unexpected",
                        illegalAccessException);
            } finally {
                if (columnWidthField != null)
                    columnWidthField.setAccessible(false);
            }
        }
    }
}

Related Tutorials