Skip to content

Instantly share code, notes, and snippets.

@runemart
Created March 26, 2014 11:57
Show Gist options
  • Save runemart/9781609 to your computer and use it in GitHub Desktop.
Save runemart/9781609 to your computer and use it in GitHub Desktop.
A GridView that uses the necessary height to wrap all of it's children, instead of scrolling
// http://www.jayway.com/2012/10/04/how-to-make-the-height-of-a-gridview-wrap-its-content/
public class WrappingGridView extends GridView {
public WrappingGridView(Context context) {
super(context);
}
public WrappingGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WrappingGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSpec = heightMeasureSpec;
if (getLayoutParams().height == LayoutParams.WRAP_CONTENT) {
// The great Android "hackatlon", the love, the magic.
// The two leftmost bits in the height measure spec have
// a special meaning, hence we can't use them to describe height.
heightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
}
super.onMeasure(widthMeasureSpec, heightSpec);
}
}
@bebop-001
Copy link

Works on my nexus 7 (Android 4.4.4) but on my phone (ZTE z665c with android 4.1.1) all I see is "Header 1"

@rafasimionato
Copy link

Hi dude, first of all thanks for sharing.
So could you please let us know which distribute license have you been associated to this class ?

@CMyae
Copy link

CMyae commented Jan 10, 2018

Hey,I don't understand this line.
heightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
How does it work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment