如何在片段和活动中创建折叠工具栏

时间:2017-02-06 09:12:17

标签: android android-collapsingtoolbarlayout

我试图在我的项目中为片段和活动创建折叠工具栏, 但崩溃的工具栏不能正常工作。请帮我找到解决方案,因为我刚接触到android。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

首先,您需要创建一个AppBar布局作为主要父级。在里面添加一个CollapsingToolbarLayout。在CollapsingToolbarLayout内部,在工具栏中添加您想要的任何内容,最后添加工具栏。

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:contentScrim="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways">

<!--This can be anything, here I've added a view pager inside collapsing toolbar-->

                <android.support.v4.view.ViewPager
                    android:id="@+id/pager_introduction"
                    android:layout_width="match_parent"
                    android:layout_height="192dp"
                    android:fitsSystemWindows="true"
                    app:layout_collapseMode="parallax"
                    tools:listitem="@layout/pager_item" />

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                    app:layout_collapseMode="pin" />

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

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

现在为android部分实例化工具栏并设置它。

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

在我的情况下,我添加了一个viewpager,必须创建一个单独的适配器来填充该viewpager。