Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@JMPergar
Created November 5, 2014 13:28
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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;
}
}
@itaispector
Copy link

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
Copy link

attrs.xml file:




@itaispector
Copy link

and this to attrs.xml file:

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

@CodingHornet
Copy link

thanks

@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