Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
}
@itaispector

This comment has been minimized.

Copy link

@itaispector itaispector commented Jul 21, 2015

Great One! consider adding this to the second constructor:

public ScrollViewWithMaxHeight(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.getTheme().obtainStyledAttributes(
            attrs,
            R.styleable.ScrollViewWithMaxHeight,
            0, 0);

    try {
        setMaxHeight(a.getInt(R.styleable.ScrollViewWithMaxHeight_maxHeight, 0));

    } finally {
        a.recycle();
    }
}

and this attrs.xml file:

Works like a charm, thank you.

@itaispector

This comment has been minimized.

Copy link

@itaispector itaispector commented Jul 21, 2015

attrs.xml file:




@itaispector

This comment has been minimized.

Copy link

@itaispector itaispector commented Jul 21, 2015

and this to attrs.xml file:

<declare-styleable name="ScrollViewWithMaxHeight">
    <attr name="maxHeight" format="integer" />
</declare-styleable>
@CodingHornet

This comment has been minimized.

Copy link

@CodingHornet CodingHornet commented Aug 11, 2015

thanks

@gturedi

This comment has been minimized.

Copy link

@gturedi gturedi commented Jan 14, 2016

declaring maxHeight as dimension better than integer

@khaledkhj

This comment has been minimized.

Copy link

@khaledkhj khaledkhj commented Nov 17, 2016

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