自定义AppBarLayout.Behavior
时间: 2024-03-17 20:45:17 浏览: 17
自定义 AppBarLayout.Behavior 可以实现更加灵活的交互效果。以下是一个简单的例子,它实现了当 RecyclerView 向下滑动时,AppBarLayout 向上滚动隐藏,向上滑动时 AppBarLayout 显示:
```java
public class CustomAppBarBehavior extends AppBarLayout.Behavior {
public CustomAppBarBehavior() {
super();
}
public CustomAppBarBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onStartNestedScroll(@NonNull CoordinatorLayout parent, @NonNull AppBarLayout child,
@NonNull View directTargetChild, @NonNull View target,
int axes, int type) {
return axes == ViewCompat.SCROLL_AXIS_VERTICAL;
}
@Override
public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout,
@NonNull AppBarLayout child,
@NonNull View target,
int dx,
int dy,
@NonNull int[] consumed,
int type) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
// 向下滑动,AppBarLayout 隐藏
if (dy > 0) {
child.setExpanded(false, true);
} else {
// 向上滑动,AppBarLayout 显示
child.setExpanded(true, true);
}
}
}
```
在这个例子中,我们重写了 onStartNestedScroll 和 onNestedPreScroll 方法,当 RecyclerView 开始垂直滑动时,我们返回 true,并在 onNestedPreScroll 方法中根据滑动方向控制 AppBarLayout 的展开和收缩。