CoordinatorLayout的幾個(gè)重要的參數(shù):
Behavior字面意思就是行為舉止递鹉,這里我們通過自定義Behavior來實(shí)現(xiàn)自己需要的效果。
首先創(chuàng)建一個(gè)類 extends Coordinator.Behavior<T>{}
釋義:childView藏斩,這個(gè)是主動(dòng)依賴的View即T
dependencyView是被依賴的View躏结,即:chidlView 會(huì)根據(jù)dependencyView的變化發(fā)生相應(yīng)的變化。-
給自定義的Behavior定義構(gòu)造方法狰域,要調(diào)用父類的有兩個(gè)參數(shù)的構(gòu)造方法如下:
public MyBehavior(Context context, AttributeSet attrs) { super(context, attrs); }
否則會(huì)報(bào)錯(cuò):Could not inflate Behavior subclass 包名.MyBehavior
- 重寫最終要的兩個(gè)方法:
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, Button child, View dependency) {
return dependency instanceof MyView;
}
//釋義:該方法是檢測被依賴的View(即dependencyView)是否是我們這里定義的View媳拴,即:MyView。返回false表示child不依賴dependency北专,ture表示依賴
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, Button child, View dependency) {
int top = dependency.getTop();
//更新childView
updateChild(child, top);
return true;
}
//釋義:這里就是監(jiān)聽 被依賴的dependencyView的變化禀挫,然后對ChildView進(jìn)行相應(yīng)的變化即可。
-
然后在CoordinatorLayout布局中加入ChildView和DependencyView拓颓,并在ChildView中加入屬性:
app:layout_behavior="com.thc.myzhihu.materialdesigndemo.MyBehavior"