在 ViewPager 中切换页面时显示工具栏

show toolbar when switching page in ViewPager

我之前搜索过 Stack Overflow,但没有找到适合我的问题的答案。

我有一个 Android 应用程序,其协调器布局内部有一个嵌套的 ViewPager。如果我滚动视图寻呼机中第一个片段内部的 RecyclerView,工具栏将按预期隐藏和显示。但是,我在 ViewPager 中的其他片段没有嵌套滚动,所以如果工具栏在 ViewPager 页面更改时隐藏,我想显示它。我想知道我是否可以扩展 CoordinatorLayout 行为来很好地完成它。

提前致谢!如果需要,我很乐意提供更多详细信息。

大概的代码是(试图去掉所有不需要的东西):main_activity.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        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.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/toolbar" />
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tab_layout"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

和一个滚动片段:fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.v7.widget.CardView
    android:id="@+id/add_word_card"
    android:orientation="horizontal"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
    <RelativeLayout
        android:id="@+id/add_word_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/highlight">
        <!-- some unrelated stuff -->
    </RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_below="@id/add_word_card"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:context=".MainActivity"/>

我发现了几个相关的问题,例如:this or this。但他们主要关注布局问题,而我想了解是否真的有一个很好的解决方案来按需触发工具栏移动。

所以答案似乎如下:将 Toolbar 包装在 AppBarLayout 中,并在代码中使用类似的内容:appBarLayout.setExpanded(false, true);

这对我有用。