AppBarLayout隐藏工具栏上的滚动行为,切换片段

时间:2016-02-24 23:10:12

标签: android android-layout android-fragments android-coordinatorlayout android-appbarlayout

我已经实现了CoordinatorLayout并将Toolbar包裹在AppBarLayout内,以便滚动时工具栏会自行隐藏。大多数应用程序都包含交换进出@id/container FrameLayout的片段,如下所示。一些片段只是RecyclerViews,而其他片段则是其他布局。我已将app:layout_behavior="@string/appbar_scrolling_view_behavior"添加到@id/container FrameLayout。继承我的主要布局:

<DrawerLayout>

     <RelativeLayout
        android:id="@+id/mainRelativeLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"  
            >

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

                <Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:elevation="5dp"
                    app:layout_scrollFlags="scroll|enterAlways"
                    >

                </Toolbar>

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

            <FrameLayout
                android:id="@+id/container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
                />

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

    </RelativeLayout>

<!-- ignore -->
<drawercontents>
</DrawerLayout>

现在,当使用Toolbar滚动片段时,RecyclerView会隐藏自身。

问题是,当切换到另一个没有RecyclerView的片段时,它会破坏片段布局。例如,如果我向下滚动容器RecyclerView的片段,Toolbar将隐藏自己(就像它应该)。然后,如果我切换到没有RecyclerView的其他片段,工具栏仍然会被隐藏,布局将扩展到额外的空间。如果我回到带有RecyclerView的片段并且不滚动(因此Toolbar保持可见),然后切换到另一个片段,现在由于{{{{{{ 1}}。

下面是该问题的截图:http://prnt.sc/a7majo

我还尝试使用以下代码禁用该片段中的滚动行为:

Toolbar

这不起作用,或者在底部生成奇怪的结果:http://prnt.sc/a7mapg

那么解决方法是什么?我已经看到了一些与此相似的其他问题,但给出的答案似乎对我的情况不起作用。提前谢谢!

1 个答案:

答案 0 :(得分:3)

protected void setScrollingEnabled(boolean isEnabled) {
    AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
    params.setScrollFlags(isEnabled ? (AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS) : 0);
}