本文是codetrick上material design support library教程的第三篇,主要讲的是CollapsingToolbarLayout的概念和应用方法。java
原文连接:Material Design Support Library Tutorial – Part 3android
想实现工具栏collpasing的效果,须要将工具栏(Toolbar)包裹在CollapsingToolbarLayout内。布局的结构以下:git
<android.support.design.widget.CoordinatorLayout > <android.support.design.widget.AppBarLayout > <android.support.design.widget.CollapsingToolbarLayout > <ImageView /> <android.support.v7.widget.Toolbar /> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <!-- Your scrollable content here --> </android.support.design.widget.CoordinatorLayout>
CoordinatorLayout是一个增强的FrameLayout,指定了子视图的多种交互行为。容许浮动的视图锚定在布局中。github
AppBarLayout是一个垂直的线性布局,实现了material design中关于app bar概念的多个特性,也就是滚动手势。windows
子视图应该经过setScrollFlags(int)
方法给出它们想要的滚动行为,相关联的布局xml属性是app:layout_scrollFlags
。app
这个控件重度依赖CoordinatorLayout,并且须要是CoordinatorLayout的直接子控件。若是你把AppBarLayout放在别的ViewGroup中,它的大多数功能都将失效。工具
CollapsingToolbarLayout是对Toolbar的包装,实现了一个能够收缩的应用栏。它被设计成做为AppBarLayout的直接子视图来使用。它包含如下的特性:布局
这个标题在布局彻底可见时最大,当布局滚出屏幕时会收缩变小。你能够经过setTitle(CharSequence)
方法来设置标题。标题文本的外观能够经过collapsedTextAppearance
和expandedTextAppearance
属性来修改。spa
一个full-bleed(满血?)的scrim(帘布?),当滚动位置到达必定阈值时会显示或者隐藏。你能够经过setContentScrim(Drawable)
方法来改变它。设计
这也是一个scrim(帘布?),当滚动位置到达必定的阈值时会显示或隐藏在状态栏(status bar)后面。你能够经过setStatusBarScrim(Drawable)
方法来改变它。在LOLLIPOP设备上,只有设置了fit system windows属性,它才有效。
在这个布局中,子视图能够选择视差滚动。参见COLLAPSE_MODE_PARALLAX
和setParallaxMultiplier(float)
。
子视图也可选择在全局空间中固定位置。在实现收缩效果时这颇有用,由于即便布局在移动,它上面的Toolbar也能够固定在一个位置。
<android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:expandedTitleMarginEnd="64dp" app:expandedTitleMarginStart="48dp" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <com.codentrick.materialdesigndemo.SquareImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:scaleType="centerCrop" app:layout_collapseMode="parallax" /> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> </android.support.design.widget.CollapsingToolbarLayout>
java代码:
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); collapsingToolbarLayout.setTitle("This is title"); collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));
相关代码和效果参见原做者的github库MaterialDesignSupportSample。