避免 ScrollView 占用过多的高度

5

我想让ScrollView不占用屏幕底部太多的空间,因为这会导致我的两个按钮无法显示。我也不希望手动设置ScrollView的高度。

<LinearLayout
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">
   <LinearLayout
      ...
      android:orientation="horizontal">
        <Button .../>
        <TextView .../>
        <Button .../>
   </LinearLayout>
   <ScrollView
      android:layout_width="math_parent"
      android:layout_height="wrap_content">
      <ImageView .../>
      <ImageView .../>
      <ImageView .../>
   </ScrollView>
   <LinearLayout
      ...
      android:orientation="horizontal">
        <Button .../>
        <Button .../>
   </LinearLayout>
</LinearLayout>

这是我的布局的概括版本。问题在于ScrollView无论其中有多少项,都会延伸到屏幕底部。这导致屏幕底部的两个按钮不可见。
如何避免手动设置ScrollView的高度?
我已经为所有视图使用了android:layout_height="wrap_content"。
这难道不应该自动分配视图的高度以适应屏幕的高度吗?
(想包含图片,但我的声望还不够高(-_-))

1
将根布局切换为RelativeLayout可能是个好主意。这样可以提供工具,使ScrollView保持在视图的中心区域,而无需显式计算其高度。 - harism
感谢您的评论。我已经实现了一个不同的解决方案,但在这个过程中我学到了更多的东西,并且我相信您的实现最适合我想做的事情。RelativeLayout将允许我将按钮锚定到屏幕底部,然后将所有其他UI对象放置在屏幕顶部和按钮之间。 - edc598
你的ScrollView应该只有一个子元素。虽然不清楚这是否导致你的问题。 - Wytze
2个回答

3
今天我解决这个问题的方法是使用RelativeLayout作为基础。将两个LinearLayout分别锚定到RelLayout的顶部和底部。然后,我会插入ScrollView,但我会确保将其布局属性设置如下:android:layout_below="topLinearLayout"android:layout_above="bottomLinearLayout"

难道不应该是“alignParentTop = true”(底部同理)? - ataulm
对于顶部的LinearLayout,您需要设置alignParentTop=true,对于底部的LinearLayout,您需要设置alignParentBottom=true,但是对于ScrollView,我所做的方式如上所示,换句话说,将ScrollView的顶部边缘锚定到顶部LinearLayout的底部边缘,底部边缘锚定到底部LinearLayout的顶部边缘。 - edc598

2
你尝试过在ScrollView中使用layout_weight吗?如果为一个元素设置了非零权重(并将相应的维度设置为0dp),那么在设置兄弟视图的测量值后,它将填充该维度中剩余的空间,例如,在此情况下,ScrollView上下的LinearLayout。抱歉,我没有Android环境进行检查,而且已经有一段时间了。
<LinearLayout
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical">

   <LinearLayout>
      ...
      Something at the top
      ...
   </LinearLayout>

   <ScrollView
      android:layout_width="match_parent"
      **android:layout_height="0dp"
      android:layout_weight="1"**>
      <ImageView .../>
      <ImageView .../>
      <ImageView .../>
   </ScrollView>

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal" >
      ...
      buttons
      ...
   </LinearLayout>
</LinearLayout>

这里是一个答案,详细介绍了关于layout_weight属性的更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接