An alternative to Daniel Bo's answer is to manually calculate the value:
private int getColumnWidth(Context context, GridView gridView) { if (android.os.Build.VERSION.SDK_INT >= 16) return gridView.getColumnWidth(); Resources res = context.getResources(); int lPad = (int)res.getDimension(R.dimen.left_padding); int rPad = (int)res.getDimension(R.dimen.right_padding); int hSpace = (int)res.getDimension(R.dimen.horizontal_spacing); int cols = gridView.getNumColumns(); int width = gridView.getWidth(); return (width - lPad - rPad + hSpace) / cols - hSpace; }
Note that this only works for APIs above 11 (Honeycomb) and assumes that you configured GridView with some values ββdefined as resources. Consider, for example, that you have a define.xml that has:
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="left_padding">4dp</dimen> <dimen name="right_padding">8dp</dimen> <dimen name="horizontal_spacing">2dp</dimen> </resources>
And then your layout xml file has:
<GridView ... android:horizontalSpacing="@dimen/horizontal_spacing" android:paddingLeft="@dimen/left_padding" android:paddingRight="@dimen/right_padding" ... />
And if you have many similar GridViews, it would be nice to put these properties in a custom style.
At least it worked for me without using reflection. Note that it will probably be too difficult to call this function often.
Hope this helps someone.
source share