CoordinatorLayout 協(xié)調(diào)布局,可以理解為功能更強(qiáng)大的 FrameLayout 布局。它在普通情況下作用和 FrameLayout 基本一致,通常適用于兩種使用方式:第一,最為界面最頂層的裝飾布局;第二,作為包含一個或多個子視圖的特定交互容器。
CoordinatorLayout 可以監(jiān)聽其所有子控件的各種事件,然后幫我們做出最為合理的響應(yīng)。
下面看一個簡單的例子,代碼如下。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestCoordinatorLayout.TestCoordinatorActivity">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@mipmap/ic_launcher_round" />
</FrameLayout>
在 FrameLayout 布局的右下角放了一個懸浮按鈕
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_coordinator);
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(v, "正在格式化...", Snackbar.LENGTH_SHORT)
.setAction("不!", new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(TestCoordinatorActivity.this, "操作已扯回", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
}
為其添加點(diǎn)擊事件,當(dāng)點(diǎn)擊按鈕時彈出一個 Snackbar 提示框。

可以看到如果使用的是普通的 FrameLayout 當(dāng)父布局則提示框彈出時會有一小部分擋住懸浮按鈕, 要是以前可以選擇調(diào)整 layout_margin 來避免這類情況的發(fā)生,但現(xiàn)在有了更優(yōu)雅的解決方法,只需將布局文件里的 FrameLayout 改成 android.support.design.widget.CoordinatorLayout 即可。
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestCoordinatorLayout.TestCoordinatorActivity">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@mipmap/ic_launcher_round" />
</android.support.design.widget.CoordinatorLayout>
- CoordinatorLayout 本身就是一個加強(qiáng)版的 FrameLayout,所以這種替換不會有任何副作用。
- Snackbar 雖然不是 CoordinatorLayout 的子控件,但是因其在調(diào)用時在 make() 里傳入了一個 View 對象,這個對象是在浮動按鈕的監(jiān)聽事件里獲取的,而浮動按鈕又是 CoordinatorLayout 中的子控件,所以 Snackbar 也能被其監(jiān)聽到。
- 修改后的運(yùn)行效果如下。

多個視圖進(jìn)行交互操作
CoordinatorLayout 通過為子控件設(shè)置交互行為 Behavior 就可以實(shí)現(xiàn)一些特殊的效果,它是 CoordinatorLayout 的一個抽象內(nèi)部類,實(shí)現(xiàn)時需要重寫相應(yīng)的方法。
- 某個 view 監(jiān)聽另一個 view 的狀態(tài)變化,例如大小、位置、顯示狀態(tài)
/**
* 在此設(shè)置需要關(guān)注的 view
*
* @param parent 當(dāng)前的 CoordinatorLayout
* @param child 設(shè)置了 layout_behavior 的 View
* @param dependency 待觀察的 View
* @return 返回 true 則關(guān)注
*/
@Override
public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
return super.layoutDependsOn(parent, child, dependency);
}
/**
* 當(dāng)所關(guān)注的 view 狀態(tài)發(fā)生改變時調(diào)用
*/
@Override
public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
return super.onDependentViewChanged(parent, child, dependency);
}
下面看一個例子,寫一個可移動的 view
public class MoveView extends View {
private int lastX;
private int lastY;
public MoveView(Context context) {
super(context);
initView();
}
public MoveView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public MoveView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView() {
setBackgroundColor(Color.BLUE);
}
// 絕對坐標(biāo)方式
@Override
public boolean onTouchEvent(MotionEvent event) {
int rawX = (int) (event.getRawX());
int rawY = (int) (event.getRawY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 記錄觸摸點(diǎn)坐標(biāo)
lastX = rawX;
lastY = rawY;
break;
case MotionEvent.ACTION_MOVE:
// 計算偏移量
int offsetX = rawX - lastX;
int offsetY = rawY - lastY;
// 在當(dāng)前l(fā)eft、top、right、bottom的基礎(chǔ)上加上偏移量
layout(getLeft() + offsetX,
getTop() + offsetY,
getRight() + offsetX,
getBottom() + offsetY);
// 重新設(shè)置初始坐標(biāo)
lastX = rawX;
lastY = rawY;
break;
}
return true;
}
}
修改之前的布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestCoordinatorLayout.TestCoordinatorActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="標(biāo)題" />
<cn.demon96.androidintensify.TestCoordinatorLayout.MoveView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center|right"
android:layout_margin="16dp" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@mipmap/ic_launcher_round" />
</android.support.design.widget.CoordinatorLayout>
運(yùn)行后滑動藍(lán)色方塊,效果如下。

現(xiàn)在新建一個 DependentBehavior 類并繼承 CoordinatorLayout.Behavior
public class DependentBehavior extends CoordinatorLayout.Behavior<View> {
public DependentBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
// 觀察自定義的 MoveView 的移動
return dependency instanceof MoveView;
}
@Override
public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
int offset = dependency.getTop() - child.getTop();
ViewCompat.offsetTopAndBottom(child, offset);
return true;
}
}
在想要實(shí)現(xiàn)聯(lián)動效果的 view 的 xml 代碼中加上 app:layout_behavior="自定義 Behavior 的包名. 自定義 Behavior"
<?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"
tools:context=".TestCoordinatorLayout.TestCoordinatorActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="標(biāo)題"
app:layout_behavior="cn.demon96.androidintensify.TestCoordinatorLayout.DependentBehavior" />
......
</android.support.design.widget.CoordinatorLayout>
運(yùn)行效果如下

書中例子
Activity
public class CoordinatorMainActivity 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; // 標(biāo)題欄Title
@Bind(R.id.main_tb_toolbar)
Toolbar mTbToolbar; // 工具欄
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coordinator_main);
ButterKnife.bind(this);
mTbToolbar.setTitle("");
// 向上或向下滑動AppBar就會觸發(fā)監(jiān)聽
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(); // 設(shè)置自動滑動(視差)效果
}
// 設(shè)置自動滑動(視差)效果
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;
}
}
}
// 設(shè)置漸變的動畫
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);
}
}
布局代碼
<?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"
tools:context=".TestCoordinatorLayout.CoordinatorMainActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/main_abl_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="500dp"
app:layout_scrollFlags="scroll|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="bottom|center"
android:layout_marginBottom="40dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="@dimen/title_margin"
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">
<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_toolbar_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:civ_border_color="@android:color/white"
app:civ_border_width="2dp"
app:layout_behavior=".TestCoordinatorLayout.AvatarImageBehavior" />
</android.support.design.widget.CoordinatorLayout>
Behavior
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; // 結(jié)束的Y軸位置
private int mStartHeight; // 開始的圖片高度
private int mFinalHeight; // 結(jié)束的圖片高度
private int mStartXPosition; // 起始的X軸高度
private int mFinalXPosition; // 結(jié)束的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) {
return dependency instanceof Toolbar; // 依賴Toolbar控件
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, CircleImageView child, View dependency) {
shouldInitProperties(child, dependency); // 初始化屬性
final int maxScrollDistance = (int) (mStartToolbarPosition - getStatusBarHeight()); // 最大滑動距離: 起始位置-狀態(tài)欄高度
float expandedPercentageFactor = dependency.getY() / maxScrollDistance; // 滑動的百分比
float distanceYToSubtract = ((mStartYPosition - mFinalYPosition)
* (1f - expandedPercentageFactor)) + (child.getHeight() / 2); // Y軸距離
float distanceXToSubtract = ((mStartXPosition - mFinalXPosition)
* (1f - expandedPercentageFactor)) + (child.getWidth() / 2); // X軸距離
float heightToSubtract = ((mStartHeight - mFinalHeight) * (1f - expandedPercentageFactor)); // 高度減小
// 設(shè)置圖片位置
child.setY(mStartYPosition - distanceYToSubtract);
child.setX(mStartXPosition - distanceXToSubtract);
// 設(shè)置圖片大小
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 (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);
if (mStartYPosition == 0) // 圖片控件豎直中心
mStartYPosition = (int) (child.getY() + (child.getHeight() / 2));
if (mFinalYPosition == 0) // Toolbar中心
mFinalYPosition = (dependency.getHeight() / 2);
if (mStartHeight == 0) // 圖片高度
mStartHeight = child.getHeight();
if (mFinalHeight == 0) // Toolbar縮略圖高度
mFinalHeight = mContext.getResources().getDimensionPixelOffset(R.dimen.image_final_width);
if (mStartToolbarPosition == 0) // Toolbar的起始位置
mStartToolbarPosition = dependency.getY() + (dependency.getHeight() / 2);
}
// 獲取狀態(tài)欄高度
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;
}
}
運(yùn)行效果

一個簡單的例子
<?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.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="170dp"
app:contentScrim="@color/colorAccent"
app:expandedTitleMarginBottom="100dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:title="我是collapsebar的標(biāo)題">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第一個固定(pin)"
android:textSize="40sp"
app:layout_collapseMode="pin" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="不設(shè)置,跟隨滑動"
android:textSize="40sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="視察效果(parallax)"
android:textSize="40sp"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="top"
android:background="#600f"
app:layout_collapseMode="pin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是toolbar" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="appbar之內(nèi),collap之外"
android:textColor="#0f0" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="@+id/n_scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="哈"
android:textColor="#0f0"
android:textSize="200sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="哈"
android:textColor="#0f0"
android:textSize="200sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="哈"
android:textColor="#0f0"
android:textSize="200sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="哈"
android:textColor="#0f0"
android:textSize="200sp" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
參考
- 《Android開發(fā)強(qiáng)化實(shí)踐》
- 《第一行代碼(第二版)》
- 《Android群英傳》
-
CoordinatorLayout高級用法-自定義Behavior
看完這篇完全可以開發(fā)5.0的高級特效了