AppBarLayout.ScrollingViewBehavior-屏幕底部视图底部

时间:2018-11-29 23:37:37

标签: android android-layout android-coordinatorlayout coordinator-layout

在将AppBarLayout与标准ScrollingViewBehavior一起使用时,默认情况下,AppBarLayout的同级将是CoordinatorLayout的高度,而兄弟姐妹的底部将在屏幕外偏离AppBarLayout的高度。

在我的用例中,NestedScrollView只是允许工具栏折叠的一种工具,同时在可折叠工具栏下方显示另一个可滚动视图(在这种情况下为碎片)。片段是包含固定视图的片段(在这种情况下为FAB)

下面的图片演示了我正在描述的问题,提供的代码是导致问题的基本XML。

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/nestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

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

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

Fab Offscreen Wrong Height, Expanded Wrong Height, Collapsed

1 个答案:

答案 0 :(得分:1)

我发现的此问题的解决方案涉及两个部分。

  1. AppBarLayout的底部添加等于NestedScrollView高度的填充。就我而言,因为AppBarLayout仅包含Toolbar,所以高度为?attr/actionBarSize
    android:paddingBottom="?attr/actionBarSize"

  2. AppBarLayout.OnOffsetChangedListener上添加自定义AppBarLayout,这会在工具栏折叠时改变NestedScrollView的高度。

    class ScrollingOffsetFixListener(
        private val nestedScrollView: NestedScrollView
    ): AppBarLayout.OnOffsetChangedListener {
    
    private var originalHeight = 0
    private var firstOffset = true
    
    override fun onOffsetChanged(layout: AppBarLayout?, offset: Int) {
        if(firstOffset) {
            firstOffset = false
            originalHeight = nestedScrollView.measuredHeight
        }
    
        val params = nestedScrollView.layoutParams
        params.height = originalHeight + (offset * -1)
    
        nestedScrollView.layoutParams = params
       }
    }
    
相关问题