Skip to content

Instantly share code, notes, and snippets.

@JMPergar
Created November 5, 2014 13:28
Show Gist options
  • Save JMPergar/439aaa3249fa184c7c0c to your computer and use it in GitHub Desktop.
Save JMPergar/439aaa3249fa184c7c0c to your computer and use it in GitHub Desktop.
ScrollView that can be configured with max height
public class ScrollViewWithMaxHeight extends ScrollView {
public static int WITHOUT_MAX_HEIGHT_VALUE = -1;
private int maxHeight = WITHOUT_MAX_HEIGHT_VALUE;
public ScrollViewWithMaxHeight(Context context) {
super(context);
}
public ScrollViewWithMaxHeight(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ScrollViewWithMaxHeight(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (maxHeight != WITHOUT_MAX_HEIGHT_VALUE
&& heightSize > maxHeight) {
heightSize = maxHeight;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.AT_MOST);
getLayoutParams().height = heightSize;
} catch (Exception e) {
LogManager.error(this, "onMesure", "Error forcing height", e);
} finally {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setMaxHeight(int maxHeight) {
this.maxHeight = maxHeight;
}
}
@gturedi
Copy link

gturedi commented Jan 14, 2016

declaring maxHeight as dimension better than integer

@khaledkhj
Copy link

Thanks for this great solution.
I am using this concept for a LinearLayout, but can we update the layout programmatically, in case you are adding and removing items?
So it can wrap its content and fit the height in case it didn't reach the maxHeight !!

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