Created
November 5, 2014 13:28
-
-
Save JMPergar/439aaa3249fa184c7c0c to your computer and use it in GitHub Desktop.
ScrollView that can be configured with max height
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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 !!