如何在Android中设置包装内容的最大高度?

2022-09-01 03:41:38

在Android中,如何创建具有最大高度的滚动视图,并包装内容,基本上它垂直包装内容,但具有最大高度?

我试过了

<ScrollView 
     android:id="@+id/scrollView1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
         android:maxHeight="200dp"
     android:layout_alignParentBottom="true" >

    <LinearLayout
        android:id="@+id/maincontainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    </LinearLayout>
</ScrollView>

但这不起作用吗?


答案 1

您可以将其添加到任何视图中(在从视图继承的类中重写 onMeasure)

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (maxHeight > 0){
        int hSize = MeasureSpec.getSize(heightMeasureSpec);
        int hMode = MeasureSpec.getMode(heightMeasureSpec);

        switch (hMode){
            case MeasureSpec.AT_MOST:
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.AT_MOST);
                break;
            case MeasureSpec.UNSPECIFIED:
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
                break;
            case MeasureSpec.EXACTLY:
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.EXACTLY);
                break;
        }
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

答案 2

我扩展了ScrollView并添加了代码来实现此功能:

https://gist.github.com/JMPergar/439aaa3249fa184c7c0c

我希望这是有用的。