在CoordinatorLayout的几个界面用法中,个人比较喜欢的是视觉差的效果,即是让其中的图片看起来能跟toolbar相互转换一样,这个效果比较新颖,在这里也只是简单的介绍这个的用法。
其中主要的布局是这样的
然后是总的布局
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="300dp" android:fitsSystemWindows="true" android:theme="@style/ThemeOverlay.AppCompat.Dark"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/toolbar_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:expandedTitleMarginStart="20dp" app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@mipmap/coorimage" app:layout_collapseMode="parallax" app:layout_collapseParallaxMultiplier="0.7" /> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin"> </android.support.v7.widget.Toolbar> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true" android:fitsSystemWindows="true" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <TextView android:layout_margin="8dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/textString" android:textSize="20sp" /> </android.support.v4.widget.NestedScrollView> </android.support.design.widget.CoordinatorLayout>
接下来再来分析,最外层的布局需要用到coordinatorLayout,它继承与线性布局,有自身的排列,然后需要一个包裹容器AppBarLayout,设置一个固定的高度,接下来,我们必须使用一个容器布局:AppBarLayout来让Toolbar响应滚动事件,如果想制造toolbar的折叠效果,我们必须把Toolbar放在CollapsingToolbarLayout中: 通常,我们我们都是设置Toolbar的title,而现在,我们需要把title设置在CollapsingToolBarLayout上,而不是Toolbar。
CollapsingToolbarLayout collapsingToolbar =(CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle("Title");
为了制造出这种图片也缩小放大效果,我们添加一个定义了app:layout_collapseMode="parallax" 属性的ImageView。scrollview中存放的是textview来放置一个段落为了滑动界面。最后是toolbar的设置,
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);
到这里这个效果差不多实现了。