ScrollView内部的布局权重无效。

54

我想在ScrollView内的LinearLayout中给几个项目分配布局权重。但是,ScrollView忽略了LinearLayoutweightSum

我的目标是使用2、1、1的权重来划分布局(总和为4),但在ScrollView内部无法正常工作。

如何解决这个布局问题?

main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" 
        android:weightSum="4">

        <LinearLayout android:id="@+id/logo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" 
            android:layout_weight="2"
            android:background="#FFFFFF" />

        <LinearLayout android:id="@+id/logo1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" 
            android:layout_weight="1"
            android:background="#000000" />


        <LinearLayout android:id="@+id/logobutton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" 
            android:layout_weight="1" 
            android:background="#4B4B4B" />

    </LinearLayout>
</ScrollView>

请看这个:Android布局权重。我认为这是同一个问题。 - user1264255
如果我只删除ScrollView,那么它可以工作,但我的问题是如果我使用ScrollView,它就无法工作。 - MIP TECH
5个回答

169
我之前也遇到了这个问题。只需在你的ScrollView中使用android:fillViewport ="true",它将填满屏幕。
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true" >

1
@MIPTECH:尝试一下这个答案。更多信息请查看Romain Guy的http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/。 - Akhil
1
谢谢,伙计。我真的一直在寻找解决方案,这正是我所需要的。 - Gintas_
竖屏模式下运行良好,但横屏模式不是一个好的解决方案,无法正确工作。 - user3402040
最佳解决方案。非常有帮助。 - Saraschandraa

3
你所做的方式是不起作用的。 ScrollView 的子视图应该设置为wrap_content。如果你将其设置为fill_parent,它将填充 ScrollView 的区域并且永远不会滚动,因为它不会比 ScrollView 更大。 layout_weight 的思想是按比例填充特定区域。
你应该将所有子LinearLayoutslayout_height设置为wrap_content或具体大小(以dp为单位),并将父LinearLayoutlayout_height设置为wrap_content 如上所述,如果它不是布局的根(第一个)元素,则需要删除附加的

xmlns:android="http://schemas.android.com/apk/res/android"

标签。

1

只需将以下内容放入您的滚动视图中:

android:fillViewport="true"


0

根据我的经验,fillviewport=true 的效果有些奇怪。

我通过将 LinearLayout 包装在另一个布局中,比如 FrameLayout,来解决这个问题。

希望这可以帮到你。


3
嗨安迪,欢迎来到StackOverflow。感谢您的回答。但是这个答案缺乏细节说明。您应该展示一个演示包装的示例。请参阅这些回答提示。谢谢。 - Elletlar

0

在你的ScrollView中添加下面这行代码,它就能正常工作了。

ScrollView中只能有一个子元素

android:fillViewport="true"

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