做爲Android的控件, CoordinatorLayout已經加入最新的HelloWorld項目中, 也是Material風格的重要組件, 協調(Coordinate)其餘組件, 實現聯動. 那麼讓咱們來看看這個動畫效果怎麼用吧?android
本文源碼的GitHub下載地址git
聯動效果github
首先新建HelloWorld項目.app
在項目的build.gradle文件中, 引入頭像控件庫和CardView庫, 在本例中會使用.ide
compile 'de.hdodenhof:circleimageview:1.3.0' compile 'com.android.support:cardview-v7:23.1.0' compile 'com.jakewharton:butterknife:7.0.1'
在activity_main.xml
中, 保留CoordinatorLayout和AppBarLayout, 從新編寫頁面.工具
android:fitsSystemWindows="true"
這句也須要去掉, 本例須要保留最上面的狀態欄(status bar), 這個屬性會致使重疊, 默認false.gradle
activity_main.xml代碼動畫
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> </android.support.design.widget.AppBarLayout> </android.support.design.widget.CoordinatorLayout>
修改主題顏色, 粉色符合風格ui
<color name="colorPrimary">#FFCCCC</color> <color name="colorPrimaryDark">#FF00FF</color>
在AppBarLayout中, 添加CollapsingToolbarLayout控件, CollapsingToolbar會滾動消失, 被ToolBar替換, 實現滾動動畫.this
<android.support.design.widget.CollapsingToolbarLayout android:layout_width="match_parent" android:layout_height="450dp" app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"> </android.support.design.widget.CollapsingToolbarLayout>
app:layout_scrollFlags
的屬性, scroll滑動, exitUntilCollapsed退出到最小, snap自動滑動動畫, 定義CollapsingToolbarLayout的滑動屬性.
CollapsingToolbarLayout劃分兩部分, 一部分大圖, 一部分文字.
<ImageView android:layout_width="match_parent" android:layout_height="300dp" android:scaleType="centerCrop" android:src="@drawable/large" app:layout_collapseMode="parallax" /> <FrameLayout android:layout_width="match_parent" android:layout_height="150dp" android:layout_gravity="bottom|center_horizontal" android:background="@color/colorPrimary" app:layout_collapseMode="parallax"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="bottom|center" android:text="@string/person_name" android:textColor="@android:color/white" android:textSize="30sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="4dp" android:text="@string/person_title" android:textColor="@android:color/white"/> </LinearLayout> </FrameLayout>
app:layout_collapseMode="parallax"
摺疊時的視差效果, 自動滑動.
效果
CollapsingToolbarLayout
添加NestedScrollView, 文字的滾動視圖.
<android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="none" app:behavior_overlapTop="30dp" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <android.support.v7.widget.CardView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="8dp" app:cardElevation="8dp" app:contentPadding="16dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:lineSpacingExtra="8dp" android:text="@string/person_intro"/> </android.support.v7.widget.CardView> </android.support.v4.widget.NestedScrollView>
app:behavior_overlapTop="30dp"
, The amount that the scrolling view should overlap the bottom of any AppBarLayout. 使ScrollView壓在AppBarLayout上面一段長度.
添加ToolBar, 滾動結束的效果圖.
<android.support.v7.widget.Toolbar android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/colorPrimary" app:layout_anchor="@id/main_fl_title" app:theme="@style/ThemeOverlay.AppCompat.Dark"> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal"> <Space android:layout_width="@dimen/image_final_width" android:layout_height="@dimen/image_final_width" /> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical" android:text="@string/person_name" android:textColor="@android:color/white" android:textSize="20sp"/> </LinearLayout> </android.support.v7.widget.Toolbar>
ToolBar是工具欄, 滑動完成時, 在最上部顯示.
Space
預留頭像的位置.
圓形頭像CircleImageView顯示(使用第三方庫)
<de.hdodenhof.circleimageview.CircleImageView android:layout_width="120dp" android:layout_height="120dp" android:layout_gravity="center" android:src="@drawable/small" app:border_color="@android:color/white" app:border_width="2dp" app:layout_behavior=".AvatarImageBehavior" />
頭像控件的滑動行爲是自定義的類, 具體行爲參考註釋. 判斷起始和終止位置, child和dependency視圖聯動, 這裏是圖像視圖和Toolbar聯動.
/** * 圖片控件位置動畫 * * @author wangchenlong */ @SuppressWarnings("unused") public class AvatarImageBehavior extends CoordinatorLayout.Behavior<CircleImageView> { private final static float MIN_AVATAR_PERCENTAGE_SIZE = 0.3f; private final static int EXTRA_FINAL_AVATAR_PADDING = 80; private int mStartYPosition; // 起始的Y軸位置 private int mFinalYPosition; // 結束的Y軸位置 private int mStartHeight; // 開始的圖片高度 private int mFinalHeight; // 結束的圖片高度 private int mStartXPosition; // 起始的X軸高度 private int mFinalXPosition; // 結束的X軸高度 private float mStartToolbarPosition; // Toolbar的起始位置 private final Context mContext; private float mAvatarMaxSize; public AvatarImageBehavior(Context context, AttributeSet attrs) { mContext = context; init(); } private void init() { bindDimensions(); } private void bindDimensions() { mAvatarMaxSize = mContext.getResources().getDimension(R.dimen.image_width); } @Override public boolean layoutDependsOn(CoordinatorLayout parent, CircleImageView child, View dependency) { // 依賴Toolbar控件 return dependency instanceof Toolbar; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, CircleImageView child, View dependency) { // 初始化屬性 shouldInitProperties(child, dependency); // 最大滑動距離: 起始位置-狀態欄高度 final int maxScrollDistance = (int) (mStartToolbarPosition - getStatusBarHeight()); // 滑動的百分比 float expandedPercentageFactor = dependency.getY() / maxScrollDistance; // Y軸距離 float distanceYToSubtract = ((mStartYPosition - mFinalYPosition) * (1f - expandedPercentageFactor)) + (child.getHeight() / 2); // X軸距離 float distanceXToSubtract = ((mStartXPosition - mFinalXPosition) * (1f - expandedPercentageFactor)) + (child.getWidth() / 2); // 高度減少 float heightToSubtract = ((mStartHeight - mFinalHeight) * (1f - expandedPercentageFactor)); // 圖片位置 child.setY(mStartYPosition - distanceYToSubtract); child.setX(mStartXPosition - distanceXToSubtract); // 圖片大小 CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams(); lp.width = (int) (mStartHeight - heightToSubtract); lp.height = (int) (mStartHeight - heightToSubtract); child.setLayoutParams(lp); return true; } /** * 初始化動畫值 * * @param child 圖片控件 * @param dependency ToolBar */ private void shouldInitProperties(CircleImageView child, View dependency) { // 圖片控件中心 if (mStartYPosition == 0) mStartYPosition = (int) (child.getY() + (child.getHeight() / 2)); // Toolbar中心 if (mFinalYPosition == 0) mFinalYPosition = (dependency.getHeight() / 2); // 圖片高度 if (mStartHeight == 0) mStartHeight = child.getHeight(); // Toolbar縮略圖高度 if (mFinalHeight == 0) mFinalHeight = mContext.getResources().getDimensionPixelOffset(R.dimen.image_final_width); // 圖片控件水平中心 if (mStartXPosition == 0) mStartXPosition = (int) (child.getX() + (child.getWidth() / 2)); // 邊緣+縮略圖寬度的一半 if (mFinalXPosition == 0) mFinalXPosition = mContext.getResources().getDimensionPixelOffset(R.dimen.abc_action_bar_content_inset_material) + (mFinalHeight / 2); // Toolbar的起始位置 if (mStartToolbarPosition == 0) mStartToolbarPosition = dependency.getY() + (dependency.getHeight() / 2); } // 獲取狀態欄高度 public int getStatusBarHeight() { int result = 0; int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = mContext.getResources().getDimensionPixelSize(resourceId); } return result; } }
添加須要使用的id, activity_main.xml
以下
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="false" tools:context=".MainActivity"> <android.support.design.widget.AppBarLayout android:id="@+id/main_abl_app_bar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.design.widget.CollapsingToolbarLayout android:layout_width="match_parent" android:layout_height="450dp" app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"> <ImageView android:id="@+id/main_iv_placeholder" android:layout_width="match_parent" android:layout_height="300dp" android:scaleType="centerCrop" android:src="@drawable/large" app:layout_collapseMode="parallax" /> <FrameLayout android:id="@+id/main_fl_title" android:layout_width="match_parent" android:layout_height="150dp" android:layout_gravity="bottom|center_horizontal" android:background="@color/colorPrimary" app:layout_collapseMode="parallax"> <LinearLayout android:id="@+id/main_ll_title_container" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="vertical"> <TextView android:layout_marginTop="@dimen/title_margin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="bottom|center" android:text="@string/person_name" android:textColor="@android:color/white" android:textSize="30sp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="4dp" android:text="@string/person_title" android:textColor="@android:color/white" /> </LinearLayout> </FrameLayout> </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:scrollbars="none" app:behavior_overlapTop="30dp" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <android.support.v7.widget.CardView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="8dp" app:cardElevation="8dp" app:contentPadding="16dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:lineSpacingExtra="8dp" android:text="@string/person_intro" /> </android.support.v7.widget.CardView> </android.support.v4.widget.NestedScrollView> <android.support.v7.widget.Toolbar android:id="@+id/main_tb_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/colorPrimary" app:layout_anchor="@id/main_fl_title" app:theme="@style/ThemeOverlay.AppCompat.Dark"> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal"> <Space android:layout_width="@dimen/image_final_width" android:layout_height="@dimen/image_final_width" /> <TextView android:id="@+id/main_tv_title" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginLeft="8dp" android:gravity="center_vertical" android:text="@string/person_name" android:textColor="@android:color/white" android:textSize="20sp" android:visibility="invisible"/> </LinearLayout> </android.support.v7.widget.Toolbar> <de.hdodenhof.circleimageview.CircleImageView android:layout_width="@dimen/image_width" android:layout_height="@dimen/image_width" android:layout_gravity="center" android:src="@drawable/small" app:border_color="@android:color/white" app:border_width="2dp" app:layout_behavior=".AvatarImageBehavior" /> </android.support.design.widget.CoordinatorLayout>
效果
頁面
在onCreate裏面設置滑動邏輯, 設置兩個動畫: 監聽AppBar的滑動, 處理Toolbar和Title的顯示; 自動滑動效果.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mTbToolbar.setTitle(""); // AppBar的監聽 mAblAppBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { int maxScroll = appBarLayout.getTotalScrollRange(); float percentage = (float) Math.abs(verticalOffset) / (float) maxScroll; handleAlphaOnTitle(percentage); handleToolbarTitleVisibility(percentage); } }); initParallaxValues(); // 自動滑動效果 }
根據滑動百分比, 設置Title和Toolbar的顯示與消失, 使用Alpha動畫.
// 處理ToolBar的顯示 private void handleToolbarTitleVisibility(float percentage) { if (percentage >= PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR) { if (!mIsTheTitleVisible) { startAlphaAnimation(mTvToolbarTitle, ALPHA_ANIMATIONS_DURATION, View.VISIBLE); mIsTheTitleVisible = true; } } else { if (mIsTheTitleVisible) { startAlphaAnimation(mTvToolbarTitle, ALPHA_ANIMATIONS_DURATION, View.INVISIBLE); mIsTheTitleVisible = false; } } } // 控制Title的顯示 private void handleAlphaOnTitle(float percentage) { if (percentage >= PERCENTAGE_TO_HIDE_TITLE_DETAILS) { if (mIsTheTitleContainerVisible) { startAlphaAnimation(mLlTitleContainer, ALPHA_ANIMATIONS_DURATION, View.INVISIBLE); mIsTheTitleContainerVisible = false; } } else { if (!mIsTheTitleContainerVisible) { startAlphaAnimation(mLlTitleContainer, ALPHA_ANIMATIONS_DURATION, View.VISIBLE); mIsTheTitleContainerVisible = true; } } } // 設置漸變的動畫 public static void startAlphaAnimation(View v, long duration, int visibility) { AlphaAnimation alphaAnimation = (visibility == View.VISIBLE) ? new AlphaAnimation(0f, 1f) : new AlphaAnimation(1f, 0f); alphaAnimation.setDuration(duration); alphaAnimation.setFillAfter(true); v.startAnimation(alphaAnimation); }
自動滑動動畫, 當到必定比例時展開或關閉.
// 設置自動滑動的動畫效果 private void initParallaxValues() { CollapsingToolbarLayout.LayoutParams petDetailsLp = (CollapsingToolbarLayout.LayoutParams) mIvPlaceholder.getLayoutParams(); CollapsingToolbarLayout.LayoutParams petBackgroundLp = (CollapsingToolbarLayout.LayoutParams) mFlTitleContainer.getLayoutParams(); petDetailsLp.setParallaxMultiplier(0.9f); petBackgroundLp.setParallaxMultiplier(0.3f); mIvPlaceholder.setLayoutParams(petDetailsLp); mFlTitleContainer.setLayoutParams(petBackgroundLp); }
最終邏輯
public class MainActivity extends AppCompatActivity { // 控制ToolBar的變量 private static final float PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR = 0.9f; private static final float PERCENTAGE_TO_HIDE_TITLE_DETAILS = 0.3f; private static final int ALPHA_ANIMATIONS_DURATION = 200; private boolean mIsTheTitleVisible = false; private boolean mIsTheTitleContainerVisible = true; @Bind(R.id.main_iv_placeholder) ImageView mIvPlaceholder; // 大圖片 @Bind(R.id.main_ll_title_container) LinearLayout mLlTitleContainer; // Title的LinearLayout @Bind(R.id.main_fl_title) FrameLayout mFlTitleContainer; // Title的FrameLayout @Bind(R.id.main_abl_app_bar) AppBarLayout mAblAppBar; // 整個能夠滑動的AppBar @Bind(R.id.main_tv_toolbar_title) TextView mTvToolbarTitle; // 標題欄Title @Bind(R.id.main_tb_toolbar) Toolbar mTbToolbar; // 工具欄 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mTbToolbar.setTitle(""); // AppBar的監聽 mAblAppBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { int maxScroll = appBarLayout.getTotalScrollRange(); float percentage = (float) Math.abs(verticalOffset) / (float) maxScroll; handleAlphaOnTitle(percentage); handleToolbarTitleVisibility(percentage); } }); initParallaxValues(); // 自動滑動效果 } // 設置自動滑動的動畫效果 private void initParallaxValues() { CollapsingToolbarLayout.LayoutParams petDetailsLp = (CollapsingToolbarLayout.LayoutParams) mIvPlaceholder.getLayoutParams(); CollapsingToolbarLayout.LayoutParams petBackgroundLp = (CollapsingToolbarLayout.LayoutParams) mFlTitleContainer.getLayoutParams(); petDetailsLp.setParallaxMultiplier(0.9f); petBackgroundLp.setParallaxMultiplier(0.3f); mIvPlaceholder.setLayoutParams(petDetailsLp); mFlTitleContainer.setLayoutParams(petBackgroundLp); } // 處理ToolBar的顯示 private void handleToolbarTitleVisibility(float percentage) { if (percentage >= PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR) { if (!mIsTheTitleVisible) { startAlphaAnimation(mTvToolbarTitle, ALPHA_ANIMATIONS_DURATION, View.VISIBLE); mIsTheTitleVisible = true; } } else { if (mIsTheTitleVisible) { startAlphaAnimation(mTvToolbarTitle, ALPHA_ANIMATIONS_DURATION, View.INVISIBLE); mIsTheTitleVisible = false; } } } // 控制Title的顯示 private void handleAlphaOnTitle(float percentage) { if (percentage >= PERCENTAGE_TO_HIDE_TITLE_DETAILS) { if (mIsTheTitleContainerVisible) { startAlphaAnimation(mLlTitleContainer, ALPHA_ANIMATIONS_DURATION, View.INVISIBLE); mIsTheTitleContainerVisible = false; } } else { if (!mIsTheTitleContainerVisible) { startAlphaAnimation(mLlTitleContainer, ALPHA_ANIMATIONS_DURATION, View.VISIBLE); mIsTheTitleContainerVisible = true; } } } // 設置漸變的動畫 public static void startAlphaAnimation(View v, long duration, int visibility) { AlphaAnimation alphaAnimation = (visibility == View.VISIBLE) ? new AlphaAnimation(0f, 1f) : new AlphaAnimation(1f, 0f); alphaAnimation.setDuration(duration); alphaAnimation.setFillAfter(true); v.startAnimation(alphaAnimation); } }
這樣聯動效果就已經顯示出來了, 在AppBar中Toolbar和Title之間的關係, 符合Material的風格, 給用戶更多的體驗. 既然已經集成到HelloWorld中, 說明Android是極力推薦使用CoordinatorLayout這種風格的.
文/SpikeKing(簡書做者) 原文連接:http://www.jianshu.com/p/97206f5973c5 著做權歸做者全部,轉載請聯繫做者得到受權,並標註「簡書做者」。