CoordinatorLayout和Behavior(一)

318 阅读1分钟

Android Design Support Library中的很多View都要求CoordinatorLayout作为父View。CoordinatorLayout本身并没有什么神奇之处,当CoordinatorLayout的子View是普通的View时,CoordinatorLayout就相当于一个普通的FrameLayout。Android Design Support Library的交互效果是通过Behavior来实现的。

创建Behavior

Behavior是一个抽象类,创建一个Behavior就是继承Behavior。Behavior有一个泛型参数,该参数就是指定了该Behavior的View。

Behavior有两个构造方法,如下: 1.public Behavior() 该构造方法是在代码中创建Behavior时调用。 2.public Behavior(Context context, AttributeSet attrs) 该构造方法是在XML布局文件中指定Behavior时调用。

Behavior的部分方法: setTag/getTag:静态方法,用来保存临时数据,保存在指定该Behavior的View的布局参数CoordinatorLayout.LayoutParams的mBehaviorTag。 onSaveInstanceState/onRestoreInstanceState: 用来保存和恢复指定该Behavior的View的状态。

指定Behavior

  • 注意:只能给CoordinatorLayout的直接子View指定Behavior。因为Behavior是保存在CoordinatorLayout.LayoutParams的mBehavior.
  • 有三种方法给CoordinatorLayout的直接子View指定Behavior。

1.代码方式

CustomBehavior customBehavior = new CustomBehavior();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) yourView.getLayoutParams();
params.setBehavior(customBehavior);

2.XML

<FrameLayout
  android:layout_height=”wrap_content”
  android:layout_width=”match_parent”
  app:layout_behavior=”.CustomBehavior” />

3.注解 当想给自定义View指定一个默认Behavior,可以用这种方法。但是这种方式的优先级低于前面两种。

@CoordinatorLayout.DefaultBehavior(CustomBehavior.class)
public class CustomFrameLayout extends FrameLayout {
}