Skip to content

Instantly share code, notes, and snippets.

@Folyd
Last active January 31, 2024 20:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Folyd/77c837c4d5a5fb458452 to your computer and use it in GitHub Desktop.
Save Folyd/77c837c4d5a5fb458452 to your computer and use it in GitHub Desktop.
A custom GridView which can wrap content.
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;
/**
* A custom GridView which can wrap content.
*/
public class WrapGridView extends GridView {
public WrapGridView(Context context) {
super(context);
}
public WrapGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WrapGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/*
* http://www.jayway.com/2012/10/04/how-to-make-the-height-of-a-gridview-wrap
* -its-content/
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSpec;
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);
} else {
// Any other height should be respected as is.
heightSpec = heightMeasureSpec;
}
super.onMeasure(widthMeasureSpec, heightSpec);
}
}
@Radiokot
Copy link

First class Android hacking, as always 👍
I think, I should ask "What workarounds and hacks have you used to do trivial tasks" on the next interview 😅

@SebastianStehle
Copy link

For me it does not work. Do I have to set anything specific in the resources?

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