CoordinatorLayout用于協調它里面的子控件處理事件,通過Behavior來實現。
那么它是怎么協調子控件的呢?
首先需要介紹CoordinatorLayout中Child、Dependency這2個View的概念:
child表示會隨著depency這個view變化而變化。好像還是不太明白,那就先擼個代碼:
- 先來個布局,以CoordinatorLayout為根布局,包含3個子控件。其中DependView為一個簡單的自定義View,它能隨著手指的滑動而滑動:
<?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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_a"
android:background="@color/colorPrimary"
android:clickable="false"
app:layout_behavior="com.chiigu.drawerlayoutsample.behavior.MyBehavior"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image"
android:layout_marginTop="100dp"
android:src="@mipmap/ic_launcher"
app:layout_behavior="com.chiigu.drawerlayoutsample.behavior.MyBehavior"
/>
<com.chiigu.drawerlayoutsample.behavior.DependView
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@color/colorAccent"
android:layout_marginTop="200dp"
android:id="@+id/view"
/>
</android.support.design.widget.CoordinatorLayout>
- 在上面的布局中可以看到,我們添加了** app:layout_behavior**的屬性,里面有一個自定義的Behavior:
- 新建一個Behavior,繼承Behavior<>,需要傳一個Child的泛型:
public class MyBehavior extends CoordinatorLayout.Behavior<View> {
}
- 實現Behavior中的2個方法:
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
//child代表CoordinatorLayout中的所有設置了 app:layout_behavior屬性的子View
//dependency代表CoordinatorLayout中所有類型為Behavior泛型的子View
//如果當前的child view需要依賴當前的dependency view,那么返回true,反之
return false;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
//如果上面方法中返回true,并且dependency view 發生任何變化,都會調用此方法
return false;
}
- 新建一個MyBehavior:
public class MyBehavior extends CoordinatorLayout.Behavior<View> {
private final int width;
public MyBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
DisplayMetrics display = context.getResources().getDisplayMetrics();
width = display.widthPixels;
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
// int id=dependency.getId();
// if(id== R.id.view)
// return true;
return true;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
int top = dependency.getTop();
int left = dependency.getLeft();
int x = width - left - child.getWidth();
int y = top;
setPosition(child, x, y);
return true;
}
private void setPosition(View v, int x, int y) {
CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams) v.getLayoutParams();
layoutParams.leftMargin = x;
layoutParams.topMargin = y;
v.setLayoutParams(layoutParams);
}
}
以上就是圖中代碼的實現。