您必须将Behavior 附加到您想要移动的View 以及Snakebar 移动
在这里我创建了一个自定义 View 并将行为附加到它
@CoordinatorLayout.DefaultBehavior(CustomView.Behavior.class)
public class CustomView extends View {
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public static class Behavior extends CoordinatorLayout.Behavior<CustomView> {
public Behavior() {
super();
}
public Behavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onAttachedToLayoutParams(@NonNull CoordinatorLayout.LayoutParams lp) {
if (lp.dodgeInsetEdges == Gravity.NO_GRAVITY) {
// This setting makes it works (learn from FloatingActionButton.Behavior)
lp.dodgeInsetEdges = Gravity.BOTTOM;
}
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, CustomView child,
View dependency) {
return false;
}
}
}
在你的布局中使用这个CustomView,它应该可以工作
FloatingActionButton 做同样的事情,它有一个内部Behavior,它使用阴影填充做更多的事情,显示/隐藏基于AppBarLayout 运动。 CoordinatorLayout 中的每一个动作都基于其 Behavior 机制
参考这里:http://saulmm.github.io/mastering-coordinator
P/S:关于Snakebar.make的使用,将CoordinatorLayout传入view参数,不要传入任何其他组件,这样会节省系统性能。如果您查看Snakebar 代码,它有一个循环,使用 view 参数来查找根视图。根视图就是它想要的:
private static ViewGroup findSuitableParent(View view) {
ViewGroup fallback = null;
do {
if (view instanceof CoordinatorLayout) {
// We've found a CoordinatorLayout, use it
return (ViewGroup) view;
} else if (view instanceof FrameLayout) {
if (view.getId() == android.R.id.content) {
// If we've hit the decor content view, then we didn't find a CoL in the
// hierarchy, so use it.
return (ViewGroup) view;
} else {
// It's not the content view but we'll use it as our fallback
fallback = (ViewGroup) view;
}
}
if (view != null) {
// Else, we will loop and crawl up the view hierarchy and try to find a parent
final ViewParent parent = view.getParent();
view = parent instanceof View ? (View) parent : null;
}
} while (view != null);
// If we reach here then we didn't find a CoL or a suitable content view so we'll fallback
return fallback;
}