我希望我有一个例子来显示它是否令人困惑,但是基本上我想做的是显示一个底部的工具栏,该工具栏始终带有固定在屏幕底部的“向右导航”按钮(例如,转到下一页),但是如果当页面(中间部分)上的内容增加时,工具栏将向下推,因此您必须滚动才能找到它。我知道这似乎很奇怪,但这是要求。最好的方法是什么?
您可以通过在内容和导航栏之间组合使用ScrollView
的android:fillViewport="true"
和具有LinearLayout
和Space
的垂直android:layout_weight="1"
来实现。
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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"
android:fillViewport="true"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#ccc"/>
<Space
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<View
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#eee"/>
</LinearLayout>
</ScrollView>
第一个视图是您要显示的任何内容的占位符,第二个视图是导航栏的占位符。您可以看到,当第一个视图较短时(高200dp),您将在顶部获得“内容”,在底部获得导航栏:
这是可行的,因为fillViewport
属性将“拉伸”子级LinearLayout
以填充屏幕,这时将存在“多余”空间,并且layout_weight
元素上的Space
属性将占用所有空间。 (请注意,尽管是ScrollView
,但在这种状态下您实际上无法滚动任何内容,因为视图被拉伸为与屏幕的确切大小一样。)
但是,当“内容”足够高以填满屏幕时,fillViewport
属性将无效,LinearLayout将不会拉伸,也不会有多余的空间可使用。因此,一旦滚动到底部,您的内容将立即填充到导航栏的边缘:
(滚动到左侧的顶部,然后滚动到右侧的底部。)