欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~
做APP开发的过程中,有很多时候,我们需要实现类似于下面这种沉浸式的体验。
沉浸式体验
一开始接触的时候,似乎大家都会觉这种体验实现起来,会比较困难。难点在于:
- 头部的背景图在推上去的过程中,慢慢的变得不可见了,整个区域的颜色变成的暗黑色,然后标题出现了。
- StatusBar变的透明,且空间可以被利用起来,看我们的图片就顶到了顶 了。
- 我们的viewpager推到actionbar的下方的时候,就固定在了actionbar的下方,不能在往上面推了。
- 底部有一个控件,随着列表的向上滑动,它退出视角范围,以便于给出更多的空间来展示列表,其实整个沉浸式体验都是为了给列表留出更多的空间来展示。
好,总结起来以上就是我们的问题,也是需要解决的,一个一个解决了,这种需求也就实现了,那么,我们如何去一步一步来解决以上的问题呢?
1、头部背景和标题的渐隐渐现
首先,我们来分析第一个问题,头部的背景图在推上去的过程中,慢慢的变得不可见了,这种听起来好像是某种collapse,因此,很容易让人想到CollapsingToolbarLayout,如果你想要比较容易的了解CollapsingToolbarLayout
应用,建议看这位兄台的文章,他给也给了一个动画,比较详细的介绍了这个的应用,例如:
CollapsingToolbarLayout
对于里面的用法,我这里不作讲解了,但是如果你不了解这个布局的应用,我强烈建议你好好了解一下,才能继续下面走,只是想说明一下,走到这里,你有一个坑需要去填,那就是我们的标题动画可以不是这样的,而且,还是标题还是居中的,注意,这里的实现,标题不是居中的,是靠左的,这本来是Android设计规范,但是设计师偏偏不买Android规范的账,因此,我们必须躺过这个坑,然后,从Stack Overflow上了解到一个issue:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/action_bar_bkgnd"
app:theme="@style/ToolBarTheme" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:id="@+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
假设,这个方式是可行的,那么要解决居中的问题后,把返回按钮改为我们的按钮样式,然后,在耍点小诡计,让title开始是透明的,并且改变返回按钮的图片:
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
//collapsingToolbarLayout.setExpandedTitleColor(Color.WHITE);
collapsingToolbarLayout.setExpandedTitleColor(Color.TRANSPARENT);
然而,假设,始终只是一个假设,实际上,这个假设不成立,我在尝试的时候,发现Toolbar中的TextView根本就不能使用android:layout_gravity="center"这种属性好吧,即使强行加上,效果也是靠左的。
那么,如何做,我的解决方式是这样的
<android.support.design.widget.AppBarLayout
android:id="@+id/appbarlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentScrim="@color/b_G6"
app:expandedTitleMarginEnd="10dp"
app:expandedTitleMarginStart="10dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/igame_arena_rank_class_header_bg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
android:src="@drawable/bg_arena_rank_class"
app:layout_constraintDimensionRatio="375:156" />
.........
</android.support.constraint.ConstraintLayout>
<andro