我有一个 FrameLayout
,其中包含用于背景的 ImageView
和 ScrollView
中的 LinearLayout
以显示所有 View 我需要。简化代码显示在下方,用于我的 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>
这个 fragment 放在我的 activity_main.xml
的 FrameLayout
中,看起来像这样
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
</FrameLayout>
当项目高度的总和大于屏幕的高度时,ScrollView
启动,我可以像预期的那样滚动 LinearLayout
中的所有项目。
问题是,当我滚动到 LinearLayout
的顶部时,最上面的 View 隐藏在状态栏后面,如下图所示:
我正在寻找的行为是这样的:
我怎样才能完成第二张图片中显示的结果?
我的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>
最佳答案
规则如下:
- 不要在
ScrollView
的子级上使用android:layout_gravity
属性。- 它会产生不需要的行为,有关详细信息,请参阅评论。
- 不要在
ScrollView
的子级上使用android:layout_height="match_parent"
- child 不想和屏幕一样大( ScrollView 视口(viewport))。重点是 child 有精确的高度或想要扩展以适应自己的内容。
- 虽然
match_parent
对于 ScrollView 的子项可能表现为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>
android:fillViewport="true"
如果 subview 小于 ScrollView ,则扩展它。
请注意 android:gravity
中缺少的 layout_
前缀。
android:gravity
告诉LinearLayout
如何将自己的子项放置在自身内部。android:layout_gravity
告诉无论父级是谁(这里是ScrollView
)如何在LinearLayout
中定位 parent 。
关于android - ScrollView 的顶部隐藏在状态栏后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48120215/