[UI]抽屉菜单DrawerLayout分析(一)[UI]抽屉菜单DrawerLayout分析(二)

     
侧拉菜单作为普遍的导航交互控件,最开头当尚未没有android官方控件时,很多辰光都是利用开源的SlidingMenu,一直没有会分析侧拉菜单的贯彻机理,本文将分析android.support.v4.widget.DrawerLayout的使和贯彻。

连续分析DrawerLayout的手势分发部分

新葡萄娱乐 1

语到手势分发,这我便是个好话题,DrawerLayout作为连续自ViewGroup得布局他好阻止手势也足以分发给子view,也就算是以onInterceptTouchEvent中举行的操作,但是他的脚还有一个onTouchEvent方法,先押何人也?追溯代码我们可以了解ViewGroup继承自View,而onTouchEvent是View的章程

    官方介绍

DrawerLayout acts as a top-level container for window content that
allows for interactive “drawer” views to be pulled out from the edge
of the window.

Drawer positioning and layout is controlled using
the android:layout_gravity attribute on child views corresponding to
which side of the view you want the drawer to emerge from: left or
right. (Or start/end on platform versions that support layout
direction.)

To use a DrawerLayout, position your primary content view as the first
child with a width and height of match_parent. Add drawers as child
views after the main content view and set
the layout_gravity appropriately. Drawers commonly
use match_parent for height with a fixed width.

DrawerLayout.DrawerListener can be used to monitor the state and
motion of drawer views. Avoid performing expensive operations such as
layout during animation as it can cause stuttering; try to perform
expensive operations during
the STATE_IDLE state. DrawerLayout.SimpleDrawerListener offers
default/no-op implementations of each callback method.

As per the Android Design guide, any drawers positioned to the
left/start should always contain content for navigating around the
application, whereas any drawers positioned to the right/end should
always contain actions to take on the current content. This preserves
the same navigation left, actions right structure present in the
Action Bar and elsewhere

DrawerLayout直译的事抽屉布局之意思,作为视窗内之顶层容器,它同意用户通过抽屉式的推拉操作,从而将视图视窗外边缘拉到屏幕外,如右图:

抽屉菜单的张和布局通过android:layout_gravity性能来控制,可选值为left、right或start、end。通过xml来布局的话,需要拿DrawerLayout作为父容器,组界面布局作为那个首先个子节点,抽屉布局虽然紧随其后作为第二只子节点,这样即便召开就是已将内容展示区和抽屉菜单区独立开来,只需要各自不简单只区域设置情节即可。android提供了部分实用的监听器,重载相关的回调方法好于菜单的并行过程被开逻辑业务。下面是一个demo布局:

 

<android.support.v4.widget.DrawerLayout

    style=”color: #8f9f36;”>xmlns:android=”http://schemas.android.com/apk/res/android”

    style=”color: #8f9f36;”>xmlns:tools=”http://schemas.android.com/tools”

    style=”color: #8f9f36;”>android:id=”@+id/drawer_layout”

    android:layout_width= style=”color: #c8352b;”>”match_parent”

    android:layout_height= style=”color: #c8352b;”>”match_parent”

    style=”color: #8f9f36;”>tools:context=”com.aven.myapplication2.app.MainActivity” style=”color: #008f00;”>>

 

    <FrameLayout

        style=”color: #8f9f36;”>android:id=”@+id/container”

       
android:layout_width= style=”color: #c8352b;”>”match_parent”

       
android:layout_height= style=”color: #c8352b;”>”match_parent” style=”color: #008f00;”>/>

 

    style=”color: #008f00;”><fragment style=”color: #8f9f36;”>android:id=”@+id/navigation_drawer”

        style=”color: #8f9f36;”>android:layout_width=”@dimen/navigation_drawer_width”

       
android:layout_height= style=”color: #c8352b;”>”match_parent”

       
android:layout_gravity= style=”color: #c8352b;”>”start”

        style=”color: #8f9f36;”>android:name=”com.aven.myapplication2.app.NavigationDrawerFragment”

        style=”color: #8f9f36;”>tools:layout=”@layout/fragment_navigation_drawer” style=”color: #008f00;”>/>

 

</android.support.v4.widget.DrawerLayout>

 

 

于是DrawerLayout的使非常简单,和过剩容器类布局一样,它本身也延续自ViewGroup,只是以其中贯彻中见面默认将第一身材节点作为内容区,第二独当抽屉菜单,所以写布局之下得铭记,好以现行的IDE已经老智能,通过引导来创造Drawerlayout时,会自动生成Activity和xml
layout布局,比如利用AndroidStudio就格外好。

 

新葡萄娱乐 2

源码分析

咱俩或先花点时间拿二者的干优先确认还持续。

DrawerLayout实例化相关辅助类

既然DrawerLayout使用是用作顶层布局layout,那先看外的构造函数:

public DrawerLayout(Context context, AttributeSet attrs, int defStyle) {

    super(context, attrs, defStyle);

    //根据屏幕分辨率密度计算最小的边距

    final float density = getResources().getDisplayMetrics().density;

    mMinDrawerMargin = (int)
(MIN_DRAWER_MARGIN * density + 0.5f);

    final float minVel = MIN_FLING_VELOCITY * density;

    //实例化视图滑动的回调接口,包括左右简单边

    mLeftCallback = new ViewDragCallback(Gravity.LEFT);

    mRightCallback = new ViewDragCallback(Gravity.RIGHT);

    //创建滑动手势的底辅助类,负责具体的滑动监听实现

    mLeftDragger =
ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mLeftCallback);

    mLeftDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);

    mLeftDragger.setMinVelocity(minVel);

    mLeftCallback.setDragger(mLeftDragger);

 

    mRightDragger =
ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mRightCallback);

    mRightDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT);

    mRightDragger.setMinVelocity(minVel);

    mRightCallback.setDragger(mRightDragger);

 

    // So that we can catch the
back button

    setFocusableInTouchMode(true);

 

    ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate());

    ViewGroupCompat.setMotionEventSplittingEnabled(this,false);

}

打构造函数中,我们发现出个别独根本之类ViewDragCallback,
ViewDragHelper,命名上来拘禁前者和滑动的回调相关,后者与view的滑操作实现有关,所以先看ViewDragHelper。

 

onInterceptTouchEvent和onTouchEvent—鸡和蛋?

恒到ViewGroup,可以窥见onInterceptTouchEvent分定义如下,从它前面一段老长之诠释就可以看出其重大及复杂性,默认的回到是false

/\**

* * Implement this method to intercept all touch screen motion
events.  This*

* * allows you to watch events as they are dispatched to your
children, and*

* * take ownership of the current gesture at any point.*

* **

* * <p>Using this function takes some care, as it has a fairly
complicated*

* * interaction with {@link View#onTouchEvent(MotionEvent)*

* * View.onTouchEvent(MotionEvent)}, and using it requires
implementing*

* * that method as well as this one in the correct way.  Events will
be*

* * received in the following order:*

* **

* * <ol>*

* * <li> You will receive the down event here.*

* * <li> The down event will be handled either by a child of
this view*

* * group, or given to your own onTouchEvent() method to handle; this
means*

* * you should implement onTouchEvent() to return true, so you will*

* * continue to see the rest of the gesture (instead of looking for*

* * a parent view to handle it).  Also, by returning true from*

* * onTouchEvent(), you will not receive any following*

* * events in onInterceptTouchEvent() and all touch processing must*

* * happen in onTouchEvent() like normal.*

* * <li> For as long as you return false from this function,
each following*

* * event (up to and including the final up) will be delivered first
here*

* * and then to the target’s onTouchEvent().*

* * <li> If you return true from here, you will not receive any*

* * following events: the target view will receive the same event but*

* * with the action {@link MotionEvent#ACTION_CANCEL}, and all
further*

* * events will be delivered to your onTouchEvent() method and no
longer*

* * appear here.*

* * </ol>*

* **

* * @param ev The motion event being dispatched down the hierarchy.*

* * @return Return true to steal motion events from the children and
have*

* * them dispatched to this ViewGroup through onTouchEvent().*

* * The current target will receive an ACTION_CANCEL event, and no
further*

* * messages will be delivered here.*

* */*

public boolean onInterceptTouchEvent(MotionEvent ev) {

    return false;

}

 

前面片截告诉我们,复写onInterceptTouchEvent方法,可以兑现监听所有的动作事件MotionEvent,在向子view传递事件前举行我们需要的操作,当然这仗的凡跟之viewgroup相关的轩然大波;同时我们需要慎重处理该函数,因为他同onTouchEvent关系甚严谨,下面是事件接受的逐条:

先是接受的之从仍下事件,down事件,他可让view处理呢堪当自我之onTouchEvent里处理,所以实现onTouchEvent并且返回true,这样onTouchEvent继续才会接到down之后的别样事件,同时onInterceptTouchEvent不会见以吸纳后续事件,因为曾换至onTouchEvent处理了。

那么什么时onInterceptTouchEvent会管承事件转换至外的onTouchEvent呢?这取决于onInterceptTouchEvent的归来值,如果回到false,所有事件还见面先分发到此地,然后再次至对象view的onTouchEvent;相反如果回到true,那么onInterceptTouchEvent将不再接受后续事件,并且目标view会收到cancel事件,接着自己之onTouchEvent几篇后续之波。

立即实在打名字来拘禁是于好理解的onInterceptTouchEvent表示于截取触摸事件的于调用的措施,既然是截取就得一直吧事件截下来后不再向后传递,这是就是是点的亚种状况,返回true,即我们团结吃了触摸事件,子view将无机会取得提拔。

新葡萄娱乐 3

大概意思就是是要是希望我消耗掉改事件就是可直接回true,这或多或少以及onTouchEvent的返类似目的。

博客园有首文章对这些事件分发做了特别好的分析:http://www.cnblogs.com/sunzn/archive/2013/05/10/3064129.html

详尽的阐释了了dispatchTouchEvent,onInterceptTouchEvent以及onTouchEvent之间的涉

而今咱们回过头来看DrawerLayout里之散发是什么勾勒的:

再次写了后边两单方式,先押onInterceptTouchEvent:

@Override

public style=”color: #c01e51;”>boolean onInterceptTouchEvent style=”color: #797979;”>(MotionEvent ev style=”color: #797979;”>) style=”color: #797979;”>{

    final style=”color: #c01e51;”>int action style=”color: #797979;”>= MotionEventCompat style=”color: #797979;”>. style=”color: #8f9f36;”>getActionMasked style=”color: #797979;”>(ev style=”color: #797979;”>);

 

    // “|” used deliberately
here; both methods should be invoked.

    final style=”color: #c01e51;”>boolean interceptForDrag style=”color: #797979;”>= mLeftDragger style=”color: #797979;”>. style=”color: #8f9f36;”>shouldInterceptTouchEvent style=”color: #797979;”>(ev style=”color: #797979;”>) style=”color: #797979;”>|

            mRightDragger. style=”color: #8f9f36;”>shouldInterceptTouchEvent style=”color: #797979;”>(ev style=”color: #797979;”>);

 

    boolean interceptForTap style=”color: #797979;”>= style=”color: #008f00;”>false style=”color: #797979;”>;

 

    switch style=”color: #797979;”>(action style=”color: #797979;”>) style=”color: #797979;”>{

        case MotionEvent style=”color: #797979;”>. style=”color: #8f9f36;”>ACTION_DOWN style=”color: #797979;”>: style=”color: #797979;”>{

            final style=”color: #c01e51;”>float x style=”color: #797979;”>= ev style=”color: #797979;”>. style=”color: #8f9f36;”>getX style=”color: #797979;”>();

            final style=”color: #c01e51;”>float y style=”color: #797979;”>= ev style=”color: #797979;”>. style=”color: #8f9f36;”>getY style=”color: #797979;”>();

            mInitialMotionX =
x;

            mInitialMotionY =
y;

            if style=”color: #797979;”>(mScrimOpacity style=”color: #797979;”>> style=”color: #797979;”>0 style=”color: #797979;”>&&

                    isContentView style=”color: #797979;”>(mLeftDragger style=”color: #797979;”>. style=”color: #8f9f36;”>findTopChildUnder style=”color: #797979;”>(( style=”color: #c01e51;”>int style=”color: #797979;”>) x style=”color: #797979;”>, style=”color: #797979;”>( style=”color: #c01e51;”>int style=”color: #797979;”>) y style=”color: #797979;”>))) style=”color: #797979;”>{

                interceptForTap =
true style=”color: #797979;”>;

            }

            mDisallowInterceptRequested style=”color: #797979;”>= style=”color: #008f00;”>false style=”color: #797979;”>;

            mChildrenCanceledTouch style=”color: #797979;”>= style=”color: #008f00;”>false style=”color: #797979;”>;

            break style=”color: #797979;”>;

        }

 

        case MotionEvent style=”color: #797979;”>. style=”color: #8f9f36;”>ACTION_MOVE style=”color: #797979;”>: style=”color: #797979;”>{

            // If we cross the
touch slop, don’t perform the delayed peek for an edge touch.

            if style=”color: #797979;”>(mLeftDragger style=”color: #797979;”>. style=”color: #8f9f36;”>checkTouchSlop style=”color: #797979;”>(ViewDragHelper style=”color: #797979;”>. style=”color: #8f9f36;”>DIRECTION_ALL style=”color: #797979;”>)) style=”color: #797979;”>{

                mLeftCallback style=”color: #797979;”>. style=”color: #8f9f36;”>removeCallbacks style=”color: #797979;”>();

                mRightCallback style=”color: #797979;”>. style=”color: #8f9f36;”>removeCallbacks style=”color: #797979;”>();

            }

            break style=”color: #797979;”>;

        }

 

        case MotionEvent style=”color: #797979;”>. style=”color: #8f9f36;”>ACTION_CANCEL style=”color: #797979;”>:

        case MotionEvent style=”color: #797979;”>. style=”color: #8f9f36;”>ACTION_UP style=”color: #797979;”>: style=”color: #797979;”>{

            closeDrawers( style=”color: #008f00;”>true style=”color: #797979;”>);

            mDisallowInterceptRequested style=”color: #797979;”>= style=”color: #008f00;”>false style=”color: #797979;”>;

            mChildrenCanceledTouch style=”color: #797979;”>= style=”color: #008f00;”>false style=”color: #797979;”>;

        }

    }

 

    return interceptForDrag
|| interceptForTap style=”color: #797979;”>|| hasPeekingDrawer style=”color: #797979;”>() style=”color: #797979;”>|| mChildrenCanceledTouch style=”color: #797979;”>;

}

 

1.先是从touch
event里面得到当前现实的action动作,MotionEventCompat.getActionMasked(ev),内部实际上做了同一次于仍在操作event.getAction() &
ACTION_MASK;

2.反省时是不是满足截取drag状态,用于决定onInterceptTouchEvent返回值,这里来只注解说是故意用了|或,而休是||或,两者分别在||只要第一独规范满足就未以执行第二单检查,二|不同,无论如何都见面用少独标准化检查一全;

3.接下来是几乎只case,根据目前的action做拍卖;

style=”font-family: Courier; font-size: 12px; color: #797979;”> style=”font-size: 12px;”> style=”color: #020202;”>ACTION_DOWN,当按照下经常 style=”color: #020202; font-family: Courier; font-size: 12px;”>记录按下点的x,y坐标值,根据条件设置当前是不是满足tap状态,具体条件有少数独,一凡 style=”font-family: Courier; font-size: 12px;”>mScrimOpacity,表示子view中在屏幕及占据的顶深幅面(0-1),二时依据坐标点的位置取改点对应的绝上层view对象,如果是预定义的content
view即DrawerLayout里的主内容展示view,也就是同时满足view在屏幕上且点击的职一直获取于了content
view上。

style=”color: #020202; font-family: Courier;”>ACTION_MOVE,当手按下后开于屏幕上活动时,如果垂直和档次及的各项移差量达到了drag
helper的阀值则无异于高居左右星星止的回调接口

style=”color: #020202; font-family: Courier;”>ACTION_CANCLE和ACTION_UP,手势结束后,关闭菜单

终极结合几独状态来十分来控制onInterceptTouchEvent返回true还是false,

未完待续

ViewDragHelper负责实现drag操作

打它们的类注释信息遭得以看来,这个helper是只辅助类,里面封装了一些造福用户拖动ViewGroup内子view的操作和状态记录方式。

/\**

* * ViewDragHelper is a utility class for writing custom ViewGroups.
It offers a number*

* * of useful operations and state tracking for allowing a user to
drag and reposition*

* * views within their parent ViewGroup.*

* */*

* *

而今来看看是helper到底是怎封装的滑动操作,从地方的实例化我们清楚此helper通过工厂方法来布局实例,工厂方法有少只如下:

/\**

* * Factory method to create a new ViewDragHelper.*

* **

* * @param forParent Parent view to monitor*

* * @param cb Callback to provide information and receive events*

* * @return a new ViewDragHelper instance*

* */*

public static ViewDragHelper create(ViewGroup forParent, Callback cb) {

    return new ViewDragHelper(forParent.getContext(), forParent, cb);

}

 

/\**

* * Factory method to create a new ViewDragHelper.*

* **

* * @param forParent Parent view to monitor*

* * @param sensitivity Multiplier for how sensitive the helper should
be about detecting*

* *                    the start of a drag. Larger values are more
sensitive. 1.0f is normal.*

* * @param cb Callback to provide information and receive events*

* * @return a new ViewDragHelper instance*

* */*

public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb) {

    final ViewDragHelper helper
= create(forParent, cb);

    helper.mTouchSlop = (int)
(helper.mTouchSlop * (1 /
sensitivity));

    return helper;

}

 

立马第二只厂子方法create就是刚刚看到底上层调用来创造helper实例的,我们传入了一个viewgroup,也就是说helper将所有我们的DrawerLayout实例引用,第二凡是一个浮点数,和drag操作的敏感性相关,数值越充分表示drag操作更易被监听,最后是一个Callback,即ViewDragCallback实例,它自己继承自ViewDragHelper.Callback,现在来拘禁helper的构造方法:

/\**

* * Apps should use ViewDragHelper.create() to get a new instance.*

* * This will allow VDH to use internal compatibility implementations
for different*

* * platform versions.*

* **

* * @param context Context to initialize config-dependent params from*

* * @param forParent Parent view to monitor*

* */*

private ViewDragHelper(Context context, ViewGroup forParent, Callback cb) {

    if (forParent == null) {

        throw new IllegalArgumentException(“Parent
view may not be null”);

    }

    if (cb == null) {

        throw new IllegalArgumentException(“Callback
may not be null”);

    }

 

    mParentView = forParent;

    mCallback = cb;

 

    final ViewConfiguration vc
= ViewConfiguration.get(context);

    finalfloat
density = context.getResources().getDisplayMetrics().density;

    mEdgeSize = (int)
(EDGE_SIZE * density + 0.5f);

 

    mTouchSlop = vc.getScaledTouchSlop();

    mMaxVelocity =
vc.getScaledMaximumFlingVelocity();

    mMinVelocity =
vc.getScaledMinimumFlingVelocity();

    mScroller = ScrollerCompat.create(context, sInterpolator);

}

首先用检测我们传入的DrawerLayout和回调Callback,不同意吗空。接下来从ViewConfiguration中得到有view的默认配置,

vc.getScaledTouchSlop是获取一个pix为单位之距离,代表view以滑行的值;

vc.getScaledMaximumFlingVelocity获取触发view
fling的极其老每秒滚动的相距,也是pix为单位;

获得view fling的不过小各个秒滚动距离,同样pix为单位;

这里发生scroll和fling,我之懂得是scroll表示手没有偏离屏幕发出的滑行效果,二fling则是着力一划,然后view自己开始滚动的效能。

说到底实例化一个Scroller,这是特意为此来拍卖滚动的一个近乎,这里用的凡扩大包里之campact类做版本兼容。

暨是DrawerLayout已经准备好有资源,接下便手势分发时候的各种调用,这同样有些留住到下一致首稿子在做分析

 

Source:

git clone https://github.com/avenwu/DrawerDemo.git