match_parent不会使用minHeight处理布局的子项

时间:2017-08-28 18:57:00

标签: android android-layout height android-layout-weight

免责声明:我无法在所有设备上重现此信息。我能够在运行4.2.1和Galaxy Tab A的Galaxy Nexus上重现它。但它并不是在运行7.0的Nexus 6上发生的。

以下是解释情况的最低范例:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#ff0000"
            android:minHeight="500dp">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#000000" />

        </FrameLayout>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="some large text here aaaaaaaaaaaaaaaaaaaaaaaaaaa"
            android:textSize="100sp" />

    </LinearLayout>

</ScrollView>

这是一个简单的布局,我希望我的父FrameLayout占用TextView留下的所有空间(这就是我android:layout_weight="1"的原因)。如果TextView的空格小于FrameLayout&#39; minHeight,则内容可滚动,而FrameLayout会粘贴到minHeight

在内容不可滚动的情况下,一切正常,但如果FrameLayout到达其minHeight并且内容变得可滚动,则子FrameLayout会因为其高度变为零而消失某种原因。

如果您查看Android Studio预览,您将始终能够看到孩子FrameLayout,但是当您运行它时(在某些设备上),您只会看到父亲&{ #39; s background。

最简单的解决方案是向孩子minHeight添加相同的FrameLayout,但就我而言,这不是一个很好的解决方案(我的孩子实际上是一个包含其他子视图的自定义视图)。

另一个解决方案是在运行时强制子高度:

private void ensureChildHeight() {
    parent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override public void onGlobalLayout() {
            if (parent.getHeight() > 0) {
                parent.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                if (parent.getHeight() == parent.getMinimumHeight()) {
                    child.getLayoutParams().height = parent.getMinimumHeight();
                    child.requestLayout();
                }
            }
        }
    });
}

但那也不是很好。有谁知道发生了什么,以及是否有更好的解决方案?经过一段时间的工作和我同事的反馈,我觉得minHeight不可靠,我应该尽可能地避免它。

0 个答案:

没有答案
相关问题