CoordinatorLayout 协调布局,可以理解为功能更强大的 FrameLayout 布局。它在普通情况下作用和 FrameLayout 基本一致,通常适用于两种使用方式:第一,最为界面最顶层的装饰布局;第二,作为包含一个或多个子视图的特定交互容器。
CoordinatorLayout 可以监听其所有子控件的各种事件,然后帮我们做出最为合理的响应。
下面看一个简单的例子,代码如下。
<?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();
}
});
}
为其添加点击事件,当点击按钮时弹出一个 Snackbar 提示框。
可以看到如果使用的是普通的 FrameLayout 当父布局则提示框弹出时会有一小部分挡住悬浮按钮, 要是以前可以选择调整 layout_margin 来避免这类情况的发生,但现在有了更优雅的解决方法,只需将布局文件里的 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 本身就是一个加强版的 FrameLayout,所以这种替换不会有任何副作用。
- Snackbar 虽然不是 CoordinatorLayout 的子控件,但是因其在调用时在 make() 里传入了一个 View 对象,这个对象是在浮动按钮的监听事件里获取的,而浮动按钮又是 CoordinatorLayout 中的子控件,所以 Snackbar 也能被其监听到。
- 修改后的运行效果如下。
多个视图进行交互操作
CoordinatorLayout 通过为子控件设置交互行为 Behavior 就可以实现一些特殊的效果,它是 CoordinatorLayout 的一个抽象内部类,实现时需要重写相应的方法。
- 某个 view 监听另一个 view 的状态变化,例如大小、位置、显示状态
/**
* 在此设置需要关注的 view
*
* @param parent 当前的 CoordinatorLayout
* @param child 设置了 layout_behavior 的 View
* @param dependency 待观察的 View
* @return 返回 true 则关注
*/
@Override
public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
return super.layoutDependsOn(parent, child, dependency);
}
/**
* 当所关注的 view 状态发生改变时调用
*/
@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);
}
// 绝对坐标方式
@Override
public boolean onTouchEvent(MotionEvent event) {
int rawX = (int) (event.getRawX());
int rawY = (int) (event.getRawY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 记录触摸点坐标
lastX = rawX;
lastY = rawY;
break;
case MotionEvent.ACTION_MOVE:
// 计算偏移量
int offsetX = rawX - lastX;
int offsetY = rawY - lastY;
// 在当前left、top、right、bottom的基础上加上偏移量
layout(getLeft() + offsetX,
getTop() + offsetY,
getRight() + offsetX,
getBottom() + offsetY);
// 重新设置初始坐标
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="标题" />
<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>
运行后滑动蓝色方块,效果如下。
现在新建一个 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;
}
}
在想要实现联动效果的 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="标题"
app:layout_behavior="cn.demon96.androidintensify.TestCoordinatorLayout.DependentBehavior" />
......
</android.support.design.widget.CoordinatorLayout>
运行效果如下
书中例子
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; // 标题栏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就会触发监听
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);
}
}
布局代码
<?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; // 结束的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) {
return dependency instanceof Toolbar; // 依赖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; // 滑动的百分比
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)); // 高度减小
// 设置图片位置
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 (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);
}
// 获取状态栏高度
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;
}
}
运行效果
一个简单的例子
<?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的标题">
<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="不设置,跟随滑动"
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之内,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开发强化实践》
- 《第一行代码(第二版)》
- 《Android群英传》
-
CoordinatorLayout高级用法-自定义Behavior
看完这篇完全可以开发5.0的高级特效了
网友评论