如何使布局垂直填充屏幕,但是当内容不合适时开始增长

问题描述 投票:0回答:1

我希望我有一个例子来显示它是否令人困惑,但是基本上我想做的是显示一个底部的工具栏,该工具栏始终带有固定在屏幕底部的“向右导航”按钮(例如,转到下一页),但是如果当页面(中间部分)上的内容增加时,工具栏将向下推,因此您必须滚动才能找到它。我知道这似乎很奇怪,但这是要求。最好的方法是什么?

android kotlin android-activity
1个回答
0
投票

您可以通过在内容和导航栏之间组合使用ScrollViewandroid:fillViewport="true"和具有LinearLayoutSpace的垂直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将不会拉伸,也不会有多余的空间可使用。因此,一旦滚动到底部,您的内容将立即填充到导航栏的边缘:

(滚动到左侧的顶部,然后滚动到右侧的底部。)

© www.soinside.com 2019 - 2024. All rights reserved.