How to set a maximum height with wrap content in android?
you can add this to any view (override onMeasure in a class inherited from a view)
@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (maxHeight > 0){ int hSize = MeasureSpec.getSize(heightMeasureSpec); int hMode = MeasureSpec.getMode(heightMeasureSpec); switch (hMode){ case MeasureSpec.AT_MOST: heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.AT_MOST); break; case MeasureSpec.UNSPECIFIED: heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST); break; case MeasureSpec.EXACTLY: heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.EXACTLY); break; } } super.onMeasure(widthMeasureSpec, heightMeasureSpec);}
I've extended ScrollView and added code to implement this feature:
https://gist.github.com/JMPergar/439aaa3249fa184c7c0c
I hope that be useful.
You can do it programmatically.
private static class OnViewGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener { private final static int maxHeight = 130; private View view; public OnViewGlobalLayoutListener(View view) { this.view = view; } @Override public void onGlobalLayout() { if (view.getHeight() > maxHeight) view.getLayoutParams().height = maxHeight; }}
And add listener to the view:
view.getViewTreeObserver() .addOnGlobalLayoutListener(new OnViewGlobalLayoutListener(view));
Listener will call method onGlobalLayout(), when view height will be changed.