android-[譯]掌握CoordinatorLayout

Google I/O 15上,谷歌發(fā)布了一個新的 support library,里面包含了一些遵循Material Design's spec的UI組件,比如,AppbarLayout, CollapsingToolbarLayoutCoordinatorLayout。
這些組件配合起來使用可以產(chǎn)生強(qiáng)大的效果,那么讓我們通過這篇文章來學(xué)習(xí)如何使用這些組件。

CoordinatorLayout

從名字可以看出,這個ViewGroup是用來協(xié)調(diào)它的子View的??聪聢D:


CoordinatorLayout
CoordinatorLayout

這個例子中的各個View相互影響,卻被和諧的組織在了一起。這就是使用`CoordinatorLayout`最簡單的實(shí)例:

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/background_light"
    android:fitsSystemWindows="true"
    >

    <android.support.design.widget.AppBarLayout
        android:id="@+id/main.appbar"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true"
        >

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/main.collapsing"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            >

            <ImageView
                android:id="@+id/main.backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                android:src="@drawable/material_flat"
                app:layout_collapseMode="parallax"
                />

            <android.support.v7.widget.Toolbar
                android:id="@+id/main.toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin"
                />
        </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"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:lineSpacingExtra="8dp"
            android:text="@string/lorem"
            android:padding="@dimen/activity_horizontal_margin"
            />
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:src="@drawable/ic_comment_24dp"
        app:layout_anchor="@id/main.appbar"
        app:layout_anchorGravity="bottom|right|end"
        />
</android.support.design.widget.CoordinatorLayout>

看一下上面Layout的結(jié)構(gòu),CoordinatorLayout包含三個子View:
一個AppbarLayout,一個scrolleable View,一個指定了??錨點(diǎn)的FloatingActionBar

<CoordinatorLayout>
    <AppbarLayout/>
    <scrollableView/>
    <FloatingActionButton/>
</CoordinatorLayout>

AppBarLayout

首先,AppBarLayout是一個LinearLayout,它的子View默認(rèn)縱向排列, 可以通過一些參數(shù)控制子View的滑動行為。這么說你還是很難理解,所以無圖無真相,上GIF:

AppBarLayout
AppBarLayout

這張圖最上面是一個可折疊圖片(collapsing image),圖片下面的藍(lán)色View就是AppBarLayout,它包含了一個Toolbar,一個有標(biāo)題和子標(biāo)題的LinearLayout,一個帶有Tab的TabLayout

<AppBarLayout>
    <CollapsingToolbarLayout
        app:layout_scrollFlags="scroll|snap"
        />

    <Toolbar
        app:layout_scrollFlags="scroll|snap"
        />

    <LinearLayout
        android:id="+id/title_container"
        app:layout_scrollFlags="scroll|enterAlways"
        />

    <TabLayout /> <!-- no flags -->
</AppBarLayout>

AppbarLayout的直接子View的操控行為,可以通過給子View添加layout_scrollFlags屬性來控制。關(guān)于這個屬性的值:scroll,在這個例子中用到了這個值。如果一個子View沒有賦值scroll,那么滑動的時候,它就會一直靜態(tài)顯示,而其他scroll的View就會被劃到它的后面隱藏。

另一個值snap的作用是避免一個View停留在動畫的中間狀態(tài),也就是說滑動結(jié)束的時候一個View要么全部顯示,要么全部隱藏,不會展示View的部分。

上面的LinearLayout指定了enterAlways,所以下拉的時候,它就會一直出現(xiàn)。TabLayout 沒有指定,所以它一直靜態(tài)顯示。

由此,給子View使用不同的layout_scrollFlags就會生成不同的AppBarLayout。全部屬性值參照官方文檔,文章最后我也會提供幾個放在Github上的實(shí)例。

AppbarLayout flags

*SCROLL_FLAG_ENTER_ALWAYS:((entering) / (scrolling on screen))下拉的時候,這個View也會跟著滑出。

*SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED:另一種enterAlways,但是只顯示折疊后的高度。

*SCROLL_FLAG_EXIT_UNTIL_COLLAPSED:((exiting) / (scrolling off screen))上拉的時候,這個View會跟著滑動直到折疊。

*SCROLL_FLAG_SCROLL:跟著滑動方向滑動。

*SCROLL_FLAG_SNAP:滑動結(jié)束的時候,如果這個View部分顯示,它就會滑動到離它最近的上邊緣或下邊緣。

CoordinatorLayout Behaviors

打開Android Studio (>= 1.4),用模版Scrolling Activity新建一個項(xiàng)目,然后直接編譯運(yùn)行??吹剑?/p>

Scrolling Activity
Scrolling Activity

查看生成的代碼,沒發(fā)現(xiàn)滑動時候Fab大小變化動畫的相關(guān)代碼,Why?
答案在FloatingActionButton的源代碼中,感謝Android Studio v1.2自帶了反編譯源代碼的功能,ctrl/cmd + click我們來FloatingActionButton的源碼中究竟干了什么。

/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 *  Floating action buttons are used for a
 *  special type of promoted action. 
 *  They are distinguished by a circled icon 
 *  floating above the UI and have special motion behaviors 
 *  related to morphing, launching, and the transferring anchor point.
 * 
 *  blah.. blah.. 
 */
@CoordinatorLayout.DefaultBehavior(
    FloatingActionButton.Behavior.class)
public class FloatingActionButton extends ImageButton {
    ...

    public static class Behavior 
        extends CoordinatorLayout.Behavior<FloatingActionButton> {

        private boolean updateFabVisibility(
           CoordinatorLayout parent, AppBarLayout appBarLayout, 
           FloatingActionButton child {

           if (a long condition) {
                // If the anchor's bottom is below the seam, 
                // we'll animate our FAB out
                child.hide();
            } else {
                // Else, we'll animate our FAB back in
                child.show();
            }
        }
    }

    ...
}

其實(shí)那個大小變化動畫是design包中的Behavior控制的,上面的CoordinatorLayout.Behavior<FloatingAcctionButton>控制顯示或隱藏FAB,interesting?

SwipeDismissBehavior

在 design support library 中,我們發(fā)現(xiàn)了SwipeDismissBehavior,有了它,我們可以在CoordinatorLayout中輕松實(shí)現(xiàn)滑動刪除功能。

swipe
swipe
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_swipe_behavior);
    mCardView = (CardView) findViewById(R.id.swype_card);

    final SwipeDismissBehavior<CardView> swipe 
        = new SwipeDismissBehavior();

        swipe.setSwipeDirection(
            SwipeDismissBehavior.SWIPE_DIRECTION_ANY);

        swipe.setListener(
            new SwipeDismissBehavior.OnDismissListener() {
            @Override public void onDismiss(View view) {
                Toast.makeText(SwipeBehaviorExampleActivity.this,
                    "Card swiped !!", Toast.LENGTH_SHORT).show();
            }

            @Override 
            public void onDragStateChanged(int state) {}
        });

        LayoutParams coordinatorParams = 
            (LayoutParams) mCardView.getLayoutParams();

        coordinatorParams.setBehavior(swipe);
    }

Custom Behaviors

自定義Behavior并不難,首先介紹兩個元素:child 和 dependency。

child
child

Childs and dependencies

要改變行為的那個View就是child,dependency是作為觸發(fā)器影響child的那個View。這個例子中child是ImageView,dependency是Toolbar,然后,Toolbar滑動的時候,ImageView跟著滑動。

gif
gif

下面開始創(chuàng)建自定義Behavior,首先,繼承CoordinatorLayout.Behavior<T>,T就是child的類型,上面例子是那個ImageView,然后我們重寫方法
*layoutDependsOn
*onDependentViewChanged
每當(dāng)UI變化的時候就會調(diào)用layoutDependsOn,鑒定完dependency后一定要返回true。上面例子中用戶一滑動就會自動調(diào)用layoutDependsOn,然后開始控制child 的行為。

 @Override
   public boolean layoutDependsOn(
      
      CoordinatorLayout parent, 
      CircleImageView, child, 
      View dependency) {

      return dependency instanceof Toolbar; 
  } 

layoutDependsOn返回true后就開始調(diào)用onDependentViewChanged,在這個方法中我們利用dependency來實(shí)現(xiàn)動畫,轉(zhuǎn)換,動作。

public boolean onDependentViewChanged(

      CoordinatorLayout parent, 
      CircleImageView avatar, 
      View dependency) {


      modifyAvatarDependingDependencyState(avatar, dependency);
   }

   private void modifyAvatarDependingDependencyState(
    CircleImageView avatar, View dependency) {
        //  avatar.setY(dependency.getY());
        //  avatar.setBlahBlat(dependency.blah / blah);
    } 

放在一起就是:

public static class AvatarImageBehavior 
   extends 
CoordinatorLayout.Behavior<CircleImageView> {

   @Override
   public boolean layoutDependsOn(

    CoordinatorLayout parent, 
    CircleImageView, child, 
    View dependency) {

       return dependency instanceof Toolbar; 
  } 

   

  public boolean onDependentViewChanged(
      
    CoordinatorLayout parent, 
    CircleImageView avatar, 
    View dependency) {

      modifyAvatarDependingDependencyState(avatar, dependency);
   }

  private void modifyAvatarDependingDependencyState(
    CircleImageView avatar, View dependency) {
        //  avatar.setY(dependency.getY());
        //  avatar.setBlahBlah(dependency.blah / blah);
    }    
}

YoungPeanut.github.io

博客

原文

Resources

Coordinator Behavior Example- Github

Coordinator Examples- Github

Introduction to coordinator layout on Android- Grzesiek Gajewski

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容