Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: why is there no maxHeight for a View?

View's have a minHeight but somehow are lacking a maxHeight:

What I'm trying to achieve is having some items (views) filling up a ScrollView. When there are 1..3 items I want to display them directly. Meaning the ScrollView has the height of either 1, 2 or 3 items.

When there are 4 or more items I want the ScrollView to stop expanding (thus a maxHeight) and start providing scrolling.

However, there is unfortunately no way to set a maxHeight. So I probably have to set my ScrollView height programmatically to either WRAP_CONTENT when there are 1..3 items and set the height to 3*sizeOf(View) when there are 4 or more items.

Can anyone explain why there is no maxHeight provided, when there is already a minHeight?

(BTW: some views, like ImageView have a maxHeight implemented.)

like image 787
znq Avatar asked Oct 29 '10 17:10

znq


People also ask

How do I clone a view?

You cannot clone views, the way to do it is to inflate your View every time. Note that the XML is compiled into binary which can be parsed very efficiently.

What are two different ways to set the height and width of component in Android?

What are two different ways to set the height and width of component in Android? First get layout params using view. getLayoutParams(). Second then set the height and width value then last set the layout params of view.


2 Answers

None of these solutions worked for what I needed which was a ScrollView set to wrap_content but having a maxHeight so it would stop expanding after a certain point and start scrolling. I just simply overrode the onMeasure method in ScrollView.

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {     heightMeasureSpec = MeasureSpec.makeMeasureSpec(300, MeasureSpec.AT_MOST);     super.onMeasure(widthMeasureSpec, heightMeasureSpec); } 

This might not work in all situations, but it certainly gives me the results needed for my layout. And it also addresses the comment by madhu.

If some layout present below the scrollview then this trick wont work – madhu Mar 5 at 4:36

like image 150
whizzle Avatar answered Sep 23 '22 00:09

whizzle


In order to create a ScrollView or ListView with a maxHeight you just need to create a Transparent LinearLayout around it with a height of what you want the maxHeight to be. You then set the ScrollView's Height to wrap_content. This creates a ScrollView that appears to grow until its height is equal to the parent LinearLayout.

like image 38
JustinMorris Avatar answered Sep 19 '22 00:09

JustinMorris