如何在安卓布局中创建固定页脚?

33
我正在使用以下代码在活动底部显示按钮。
<RelativeLayout 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignParentBottom="true" 
        android:layout_centerHorizontal="true" 
         >
    <Button android:id="@+id/btnGetMoreResults"
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 

         android:text="Get more"
       />
       </RelativeLayout> 

我有一个放在listview上方的按钮面板,但是当我在listview中显示更多数据时,这个按钮面板会被移动到下方。有没有人能指导我如何将其固定在活动的底部?

非常感谢任何帮助。

3个回答

99
被选为正确答案的回答是有问题的,该按钮将隐藏列表视图的下部。正确的方法是先声明按钮,然后将列表定位在按钮上方。
<Button android:id="@+id/btnGetMoreResults"
   android:layout_height="wrap_content" 
   android:layout_width="wrap_content"     
   android:text="Get more"
   android:layout_alignParentBottom="true"/>

<ListView 
   ...
   android:layout_above="@id/btnGetMoreResults"/>

26

android:layout_alignParentBottom属性必须在RelativeLayout元素中声明,而不是在RelativeLayout本身中声明(除非有另一个RelativeLayout作为父容器)。你应该像这样做,将ListView放在RelativeLayout中:

<RelativeLayout 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content"         
 android:layout_centerHorizontal="true">
  <ListView ...>
  <Button android:id="@+id/btnGetMoreResults"
   android:layout_height="wrap_content" 
   android:layout_width="wrap_content"     
   android:text="Get more"
   android:layout_alignParentBottom="true" />
</RelativeLayout> 

我之前试了好几个小时,但这个立刻就起作用了 :) - ani0904071

9

举例来说,如果你的所有可滚动元素都在一个ScrollView中,你应该按照以下方式进行操作:

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
    android:layout_height="match_parent"
        style="@style/rootElement"
    >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

            <!-- texts, buttons, images and anything that you want to scroll -->

        </ScrollView>

    <LinearLayout 
        android:orientation="vertical" 
        style="@style/footer"
        android:id="@+id/footer"            
            android:layout_alignParentBottom="true"
        >

    </LinearLayout>

</RelativeLayout>

请注意,如果您希望页脚固定,则不应将其放在 ScrollView 中,其中将放置可滚动内容。将其作为 RelativeLayout 的子项,并将 layout_alignParentBottom 设置为 true。在此情况下,您可能需要在 ScrollView 底部添加填充(以便最后一个元素不被页脚隐藏)。对于除了 ScrollView 之外的其他元素,思路是类似的。

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