android layout maxHeight

来源:互联网 发布:爱普生打印软件下载 编辑:程序博客网 时间:2024/06/06 03:06

如何实现一个view或者layout,使它有一个最大高度?也就是说

  • 当view的高度小于一个固定值(MAX_HEIGHT)时,view的高度采用自身高度(wrap_content)。
  • 当view的高度大于一个固定值(MAX_HEIGHT)时,view的高度设置为MAX_HEIGHT,并且可以scroll。
我就写了这样一个layout:
<ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent">    <RelativeLayout        android:id="@+id/content_body"        android:layout_width="match_parent"        android:layout_height="match_parent" /></ScrollView>
但是无论我怎么设置ScrollView和子layout的layout_width和layout_height属性都无法达到上面的要求。
于是我回忆起android layout里好像有"maxHeight"属性,结果找了半天,发现只有一个“minHeight”属性。

没办法了,只能自己动手。
自定义一个ScrollView并且重载onMeasure方法。问题解决!
public class AutoFitScrollView extends ScrollView {    private static final int MAX_HEIGHT = 300;        @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        View child = getChildAt(0);        child.measure(widthMeasureSpec, heightMeasureSpec);        int width = child.getMeasuredWidth();        int height = Math.min(child.getMeasuredHeight(), MAX_HEIGHT);        setMeasuredDimension(width, height);    }}





0 0