Last active
January 31, 2024 20:54
-
-
Save Folyd/77c837c4d5a5fb458452 to your computer and use it in GitHub Desktop.
A custom GridView which can wrap content.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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
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 😅