【Android】 CoordinatorLayout的使用

Coordinator Layout是Android支援API 21以上的一種ViewGroup。主要用來協調它裡面View的行為。

打開Android Studio(version>=1.4),選擇Scroll Activity,建立一個新的Project。打開 activity_scrolling.xml


由以上的code可看出CoodinatorLayout裡面有AppBarLayout,而AppBarLayout中有CollapsingToolbarLayout。其中可以通過設置

layoutscrollFlags參數,來控制View的行為。這邊的scroll|exitUntilCollapsed指的是,向上移動Screen時,View會一直收縮到最小高度後,再移出Screen。其他的行為可以參考:[AppBarLayout LayoutScrollFlags]

接下來是CollapsingToolbarLayout,顧名思義就是控制折疊Toolbar的Layout,可以設置layout collapse Mode它有兩個 Mode 可以控制分別為

  • pin : 設置這個 Mode時,當CollapsingToolbarLayout完全收縮時,ToolBar保留在畫面上。
  • parallax : 當設置這個 Mode時,滑動畫面時,CollapsingToolBarLayou中的View(ex:ImageView)也會同時滾動,並且漸漸地消失,達成一種視差的效果

下面提供Code,使用上述兩個 Mode

以上要注意的是ImageView要設置在Toolbar之上,不然不會有效果。原因是因為CollapsingToolbarLayout extends FrameLayout

大家可以試看看,藉由這樣簡單的設置,即可達成不錯的效果。
裡面還有許多參數可以使用,建議大家透過設計需求來練習,較容易快速上手!

)

    Written by

    Android Developer @ Travelstart

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade