Android RelativeLayout:如何在ScrollView中包装alignParentBottom?

Joh*_*ock 31 android

我遇到的问题似乎是,如果我在RelativeLayout中设置了一个视图(例如myButton),设置为alignParentBottom - (根据下面的代码) - 然后使用scrollview包装RelativeLayout(必要时内容将在较小的屏幕或方向更改为横向时 - 然后,当父母底部不可见时(例如,当更改为横向时)myButton显示在页面的顶部 - 而不是底部.

如何将视图与屏幕底部对齐并使其保持在底部,即使底部位于滚动下方?

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



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



... lots of views and stuff


<Button android:layout_alignParentBottom="true" 
android:id="@+id/myButton"  
android:text="Click Me" />

</RelativeLayout>
</ScrollView>   
Run Code Online (Sandbox Code Playgroud)

小智 26

从SCrollview中取出按钮,将Scrollview和Button包裹在线性布局中,将scrollview的高度设置为0dip并将其权重设置为1,不要为按钮设置任何权重属性,因此scrollview可以占用所有剩余空间只保存按钮在底部的空间方式.

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

    <ScrollView 
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

        ....lots of views...


        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="Button" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

  • 但这会使`Button'始终保持在屏幕的底部,即使`ScrollView`是可滚动的,对吧? (7认同)

Rom*_*Guy 7

使用fill_parent作为ScrollView子级的高度是没有意义的.您告诉RelativeLayout始终与其父级一样高.在这种情况下,ScrollView变得无用!RelativeLayout的高度应该设置为wrap_content,在这种情况下,根据RelativeLayout包含的内容,alignParentBottom可能无法按预期工作.你应该简单地使用LinearLayout,它会简单得多.