support designMaterial DesignAndroid知识

Material之CoordinatorLayout + Beh

2016-12-19  本文已影响2207人  风少侠

最新项目中用到了些Material效果,在此对自己的学习做个小结。

首先养成良好的学习习惯-----看源码:

CoordinatorLayout

/**
 * CoordinatorLayout is a super-powered {@link android.widget.FrameLayout FrameLayout}.
 *
 * <p>CoordinatorLayout is intended for two primary use cases:</p> 
 * <ol>
 *     <li>As a top-level application decor or chrome layout</li> 
 *     <li>As a container for a specific interaction with one or more child views</li> 
 * </ol> 
 * 
 * <p>By specifying {@link CoordinatorLayout.Behavior Behaviors} for child views of a 
 * CoordinatorLayout you can provide many different interactions within a single parent and those 
 * views can also interact with one another. View classes can specify a default behavior when 
 * used as a child of a CoordinatorLayout using the 
 * {@link CoordinatorLayout.DefaultBehavior DefaultBehavior} annotation.</p> 
 * 
 * <p>Behaviors may be used to implement a variety of interactions and additional layout 
 * modifications ranging from sliding drawers and panels to swipe-dismissable elements and buttons 
 * that stick to other elements as they move and animate.</p> 
 * 
 * <p>Children of a CoordinatorLayout may have an 
 * {@link CoordinatorLayout.LayoutParams#setAnchorId(int) anchor}. This view id must correspond 
 * to an arbitrary descendant of the CoordinatorLayout, but it may not be the anchored child itself 
 * or a descendant of the anchored child. This can be used to place floating views relative to 
 * other arbitrary content panes.</p> 
 */
public class CoordinatorLayout extends ViewGroup implements NestedScrollingParent {

大概的翻译如下:

Behavior:

/**
 * Interaction behavior plugin for child views of {@link CoordinatorLayout}. 
 * 
 * <p>A Behavior implements one or more interactions that a user can take on a child view.
 * These interactions may include drags, swipes, flings, or any other gestures.</p>
 *
 * @param <V> The View type that this Behavior operates on
 */
public static abstract class Behavior<V extends View> {

老规矩:

基本使用:

新建一个HelloWorld,选择BasicActivity,可以看到默认生成的布局中已经包含了CoordinatorLayout,说明Goolge官方非常推荐使用这种布局。
官方给出的Behavior实现类有4个:

Behavior实现类

BottomSheetBehavior

一般用于底部弹出框,类似于微信支付的效果,使用方法如下:

xml布局

<android.support.design.widget.CoordinatorLayout
  ......
>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/nestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:background="@drawable/mv"
        app:layout_behavior="@string/bottom_sheet_behavior"
        app:behavior_peekHeight="0dp"
        app:behavior_hideable="true">
        <!--中间可以随意写自己的布局-->
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:layout_behavior="cn.lxf.behaviortext.FloatingBehavior"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Activity代码

scrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
          BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(scrollView);
          bottomSheetBehavior.setState(bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED?BottomSheetBehavior.STATE_EXPANDED:BottomSheetBehavior.STATE_COLLAPSED);
     }
});

效果图:

bottomSheetBehavior

实现的关键点:

SwipeDismissBehavior

官方实现为Snackbar,已经封装好,唯一的条件是根布局必须为CoordinatorLayout,否则没有效果。
  使用方式很简单:

Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();

FloatingActionButton.Behavior

FloatingActionButton默认使用FloatingActionButton.Behavior,同Snackbar一样,唯一需要注意的是根布局必须为CoordinatorLayout。

@CoordinatorLayout.DefaultBehavior(FloatingActionButton.Behavior.class)
public class FloatingActionButton extends VisibilityAwareImageButton {
<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />
Snackbar + FloatingActionButton效果图

ViewOffsetBehavior

官方实现为AppBarLayout中的Beihavior。


AppBarLayout官方文档

挑重点:


        /**
         * The view will be scroll in direct relation to scroll events. This flag needs to be
         * set for any of the other flags to take effect. If any sibling views
         * before this one do not have this flag, then this value has no effect.
         */
        public static final int SCROLL_FLAG_SCROLL = 0x1;

        /**
         * When exiting (scrolling off screen) the view will be scrolled until it is
         * 'collapsed'. The collapsed height is defined by the view's minimum height.
         *
         * @see ViewCompat#getMinimumHeight(View)
         * @see View#setMinimumHeight(int)
         */
        public static final int SCROLL_FLAG_EXIT_UNTIL_COLLAPSED = 0x2;

        /**
         * When entering (scrolling on screen) the view will scroll on any downwards
         * scroll event, regardless of whether the scrolling view is also scrolling. This
         * is commonly referred to as the 'quick return' pattern.
         */
        public static final int SCROLL_FLAG_ENTER_ALWAYS = 0x4;

        /**
         * An additional flag for 'enterAlways' which modifies the returning view to
         * only initially scroll back to it's collapsed height. Once the scrolling view has
         * reached the end of it's scroll range, the remainder of this view will be scrolled
         * into view. The collapsed height is defined by the view's minimum height.
         *
         * @see ViewCompat#getMinimumHeight(View)
         * @see View#setMinimumHeight(int)
         */
        public static final int SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED = 0x8;

        /**
         * Upon a scroll ending, if the view is only partially visible then it will be snapped
         * and scrolled to it's closest edge. For example, if the view only has it's bottom 25%
         * displayed, it will be scrolled off screen completely. Conversely, if it's bottom 75%
         * is visible then it will be scrolled fully into view.
         */
        public static final int SCROLL_FLAG_SNAP = 0x10;
scroll scroll+exitUntilCollapsed scroll+enterAlways scroll+enterAlways+enterAlwaysCollapsed scroll+enterAlways+snap

自定义Behavior

自定义Behavior一般有两种情况:

上面这两句话出自亓斌大神博客,然后我自己在学习过程中做了些实践。
  首先看第一种,其实就是上面那个例子,FloatingActionButton怎么跟随自己的布局上下移动?很明显,这个效果类似于系统提供的FloatingActionButton+Snackbar的效果,看一下FloatingActionButton.Behavior源码(只贴了关键部分):

       /**
         * Determine whether the supplied child view has another specific sibling view as a
         * layout dependency.
         *
         * <p>This method will be called at least once in response to a layout request. If it
         * returns true for a given child and dependency view pair, the parent CoordinatorLayout
         * will:</p>
         * <ol>
         *     <li>Always lay out this child after the dependent child is laid out, regardless
         *     of child order.</li>
         *     <li>Call {@link #onDependentViewChanged} when the dependency view's layout or
         *     position changes.</li>
         * </ol>
         *
         * @param parent the parent view of the given child
         * @param child the child view to test
         * @param dependency the proposed dependency of child
         * @return true if child's layout depends on the proposed dependency's layout,
         *         false otherwise
         *
         * @see #onDependentViewChanged(CoordinatorLayout, android.view.View, android.view.View)
         */
        @Override
        public boolean layoutDependsOn(CoordinatorLayout parent,
                FloatingActionButton child, View dependency) {
            // We're dependent on all SnackbarLayouts (if enabled)
            return SNACKBAR_BEHAVIOR_ENABLED && dependency instanceof Snackbar.SnackbarLayout;
        }

        @Override
        public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child,
                View dependency) {
            if (dependency instanceof Snackbar.SnackbarLayout) {
                updateFabTranslationForSnackbar(parent, child, dependency);
            } else if (dependency instanceof AppBarLayout) {
                // If we're depending on an AppBarLayout we will show/hide it automatically
                // if the FAB is anchored to the AppBarLayout
                updateFabVisibility(parent, (AppBarLayout) dependency, child);
            }
            return false;
        }
public class FloatingBehavior extends FloatingActionButton.Behavior {

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) {
        return super.layoutDependsOn(parent, child, dependency) || dependency instanceof NestedScrollView;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
        if (dependency instanceof NestedScrollView) {
            CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
            int fab_BM = lp.bottomMargin;
            int distance = fab.getHeight() + fab_BM;
            fab.setY(dependency.getY() - distance);
        }
        return super.onDependentViewChanged(parent, fab, dependency);
    }
}

为Fab设置好改behavior后直接运行,发现报错:Could not inflate Behavior subclass cn.lxf.behaviortext.FloatingBehavior,不能实例化该behavior。一番求证后发现,自定义behavior时必须重写那个带2个参数的构造方法,因为在CoordinatorLayout中是通过反射这个构造方法来实例化behavior的,下面贴完整代码:

public class FloatingBehavior extends FloatingActionButton.Behavior {

    public FloatingBehavior(Context context, AttributeSet attrs) {

    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) {
        return super.layoutDependsOn(parent, child, dependency) || dependency instanceof NestedScrollView;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
        if (dependency instanceof NestedScrollView) {
            CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
            int fab_BM = lp.bottomMargin;
            int distance = fab.getHeight() + fab_BM ;
            fab.setY(dependency.getY() - distance);
        }
        return super.onDependentViewChanged(parent, fab, dependency);
    }
}

再看第二种情况,某个view监听CoordinateLayout中的滑动状态,这里最好先了解一下android Lollipop版本之后新增的嵌套滑动机制,推荐我学习过的一篇文章https://segmentfault.com/a/1190000002873657
  对于监听滑动状态,我们需要关注的总共有以下几个方法(由于篇幅原因,官方注释被我干掉了,加了简单的注解):

    /**
     * 当一个CoordinatorLayout的子view准备去开始一个嵌套滑动时调用
     *
     * @param coordinatorLayout  根布局coordinatorLayout
     * @param child 这个behavior所关联的coordinatorLayout的子view
     * @param directTargetChild 包含target 嵌套滚动操作的coordinatorLayout子view
     * @param target 开始嵌套滑动的coordinatorLayout子view。
     * @param nestedScrollAxes 嵌套滚动的轴线。See
     *                         {@link ViewCompat#SCROLL_AXIS_HORIZONTAL},
     *                         {@link ViewCompat#SCROLL_AXIS_VERTICAL}
     * @return 如果behavior希望接受这个嵌套滚动,则返回true。
     *
     * @see NestedScrollingParent#onStartNestedScroll(View, View, int)
     */
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
                                       V child, View directTargetChild, View target, int nestedScrollAxes) {
        return false;
    }

    /**
     * 当嵌套滑动已经被CoordinatorLayout接受时调用。
     *
     * 参数同上。
     * @see NestedScrollingParent#onNestedScrollAccepted(View, View, int)
     */
    public void onNestedScrollAccepted(CoordinatorLayout coordinatorLayout, V child,
                                       View directTargetChild, View target, int nestedScrollAxes) {
        // Do nothing
    }

    /**
     * 嵌套滚动结束时调用。
     *
     * 参数同上。
     *
     * @see NestedScrollingParent#onStopNestedScroll(View)
     */
    public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target) {
        // Do nothing
    }

    /**
     * target滑动之后调用
     *
     * @param coordinatorLayout 同上
     * @param child 同上
     * @param target 同上
     * @param dxConsumed 水平方向target滑动的距离(消耗的距离px),左滑大于0,右滑小于0
     * @param dyConsumed 垂直方向target滑动的距离(消耗的距离px),上滑大于0,下滑小于0
     * @param dxUnconsumed 水平方向target未滑动的距离(但是被用户请求了)
     * @param dyUnconsumed 垂直方向target未滑动的距离(但是被用户请求了)
     *
     * @see NestedScrollingParent#onNestedScroll(View, int, int, int, int)
     */
    public void onNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target,
                               int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
        // Do nothing
    }

    /**
     * target准备滑动时(滑动之前)调用
     *
     * @param coordinatorLayout 同上
     * @param child 同上
     * @param target 同上
     * @param dx 水平方向target想要滑动的距离(用户请求的)
     * @param dy 垂直方向target想要滑动的距离(用户请求的)
     * @param consumed 需要我们自己传入。 consumed[0] 已经被消费的水平方向滑动的距离, consumed[1] 已经被消费的垂直方向滑动的距离
     *
     * @see NestedScrollingParent#onNestedPreScroll(View, int, int, int[])
     */
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, V child, View target,
                                  int dx, int dy, int[] consumed) {
        // Do nothing
    }

    /**
     * target在fling(飞速滚动)之后调用
     *
     * @param coordinatorLayout 同上
     * @param child 同上
     * @param target 同上
     * @param velocityX 水平方向的速度
     * @param velocityY 垂直方向的速度
     * @param consumed child是否fling了
     * @return behavior是否消费了这个fling
     *
     * @see NestedScrollingParent#onNestedFling(View, float, float, boolean)
     */
    public boolean onNestedFling(CoordinatorLayout coordinatorLayout, V child, View target,
                                 float velocityX, float velocityY, boolean consumed) {
        return false;
    }

    /**
     * target在fling(飞速滚动)之前调用
     *
     * 参数同onNestedFling方法。
     *
     * @see NestedScrollingParent#onNestedPreFling(View, float, float)
     */
    public boolean onNestedPreFling(CoordinatorLayout coordinatorLayout, V child, View target,
                                    float velocityX, float velocityY) {
        return false;
    }

还是看上面那个FloatingActionButton的例子,改成上滑消失,下滑显示,代码如下:

public class FloatingBehavior extends FloatingActionButton.Behavior {

    private boolean isAniming;

    public FloatingBehavior(Context context, AttributeSet attrs) {

    }

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL;
    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
        if (dyConsumed > 0 && !isAniming && child.getVisibility() == View.VISIBLE) {
            hide(child);
        } else if (dyConsumed < 0 && !isAniming && child.getVisibility() == View.INVISIBLE) {
            show(child);
        }
    }

    private void show(final View view){
        ValueAnimator animator = ValueAnimator.ofFloat(0,1);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float f = (float) animation.getAnimatedValue();
                view.setScaleX(f);
                view.setScaleY(f);
            }
        });
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                view.setVisibility(View.VISIBLE);
                isAniming = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isAniming = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                isAniming = false;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }

    private void hide(final View view){
        ValueAnimator animator = ValueAnimator.ofFloat(1,0);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float f = (float) animation.getAnimatedValue();
                view.setScaleX(f);
                view.setScaleY(f);
            }
        });
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isAniming = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.INVISIBLE);
                isAniming = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                isAniming = false;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }
}

效果图:

监听CoordinatorLayout中的滑动状态

Demo地址

上一篇下一篇

猜你喜欢

热点阅读