ScrollView的顶部隐藏在状态栏后面

etr*_*sks 2 android statusbar android-layout android-scrollview

我有一个FrameLayout 包含ImageView背景和LinearLayout内部ScrollView显示我需要的所有视图。简化的代码显示在下面,用于Fragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"     
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ink"
        android:scaleType="center"/>

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

        <LinearLayout
            android:id="@+id/linear_layout_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical">
        </LinearLayout>

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

这个片段放在FrameLayout我的activity_main.xml里面,看起来像这样

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

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    >
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

当项目高度的总和变得大于屏幕的高度时ScrollView,我可以LinearLayout像预期的那样滚动我拥有的所有项目。

问题是,当我滚动到的顶部时LinearLayout,最上面的“视图”隐藏在状态栏中,如下图所示:

我正在寻找的行为是这样的:

视图的顶部在状态栏下方,并且完全可见。

如何完成第二张图所示的结果?

我的styles.xml如下

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

Eug*_*nec 5

以下是要遵循的规则:

  • 请勿android:layout_gravity在的子级上使用属性ScrollView
    • 它会产生有害的行为,有关详细信息,请参见注释。
  • 请勿用于android:layout_height="match_parent"以下儿童ScrollView
    • 子级不想和屏幕一样大(滚动视图视口)。重点是孩子的身高准确,或者想要扩展以适合自己的内容。
    • 虽然match_parent可能像wrap_content滚动视图的子级那样工作,但从哲学上讲,在这里没有意义。

如果您需要将内容放在整个屏幕的中心,在不适合显示内容时允许滚动,请使用以下设置:

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="vertical">
        <!-- Etc. -->
    </LinearLayout>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)

android:fillViewport="true" 如果子项小于滚动视图,则将其展开。

请注意,缺少layout_前缀android:gravity

  • android:gravity讲述了LinearLayout如何在自己的内部放置自己的孩子。
  • android:layout_gravity告诉父母(在这里ScrollView是谁,如何LinearLayout在父母中定位。