【问题标题】:Height of layouts inside of a viewpager whose height is set to wrap contentviewpager 内的布局高度,其高度设置为包裹内容
【发布时间】:2018-08-08 21:37:34
【问题描述】:

我在设置 android:height="wrap_content" 时遇到了 ViewPager 的高度设置不正确的问题

现在,我已成功应用提到的修复程序here,它按预期工作。我的 ViewPager 正确地假设了它的最高元素的高度。

但是!我的 viewpager 中的每个项目都包含一个线性布局,其中包含 2 个元素,如下所示:(这是我的容器)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <ImageView
        android:layout_margin="@dimen/gutterSpaceHalf"
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:id="@+id/foo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:layout_gravity="bottom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>

这实际上给了我一个看起来像这样的布局:

我在这里要说明的是,在第二页上,LinearLayout foo 的高度与第一页不同。这是意料之中的。

但是当我想将每个页面上的按钮对齐到底部时,问题就来了!这当然是一个问题,因为第一页上foo 的底部与第二页上foo 的底部不同。

在我看来,标准解决方案是将foo 的高度设置为match_parent。但是,如果我这样做,整个页面就会变成我的 imageview 的高度,因为上面提到的应用修复无法再正确计算每个孩子的高度。

因此,请记住,我的整个目标是拥有等高的页面,具有动态内容(文本),同时保持按钮与页面底部对齐,您会在这里建议什么解决方案?

我尝试过的事情包括在树上调整布局的高度设置,并将每个视图的高度设置为其容器的测量高度,然后将其添加到我的 ViewPagerAdapter 中,但似乎没有什么能按我想要的方式工作到。

任何建议将不胜感激。如果我遗漏了什么或者您想查看更多信息,请发表评论。

【问题讨论】:

    标签: android android-layout android-viewpager android-linearlayout


    【解决方案1】:

    我做到了,是的

    我所要做的就是在我的按钮上方添加一个带有weight=1 的视图,并给我的按钮一个静态高度。现在,由于添加的视图扩展以填充剩余大小,因此每个页面上的按钮都正确排列到底部。

    我还必须将 +1 添加到我上面提到的“hacky”解决方案中定义的高度,否则我添加的视图会将项目推出最大页面的布局,如下所示:

        if (height != 0) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + 1 /* This is a heuristic solution */, MeasureSpec.EXACTLY);
        }
    

    是的SSSSSS

    (布局更改):

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
        <View  <!-- ADDED -->
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="@dimen/buttonHeight"/>
    

    【讨论】:

    • 您说您使用weight=0 添加了视图,但您的视图中有weight=1 在您的答案中 - 请您告知它是哪一个?
    • 谢谢,它是 weight=1,我还在答案中添加了细节。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2014-12-31
    • 2021-08-28
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多