Each Navigation Drawer Hides a ViewDragHelper

转自 http://flavienlaurent.com/blog/2013/08/28/each-navigation-drawer-hides-a-viewdraghelper/

Recently, at the Google I/O 2013, two new layouts have been introduced: SlidingPaneLayout, a view that can be dragged from bottom to top and vice versa and the DrawerLayout, now used in almost all Google applications. Both of these use a new concept to more easily manage dragging: the ViewDragHelper.

In this article, I’m going to talk about the ViewDragHelper (aka VDH) because making a custom layout with dragging child view may be pain sometimes. First, I will show you how to use it and how it works (the main lines). Secondly, I will expose you a use case where the VDH is really useful.

You can download & install the sample application.

Download Sample Application

API design

In a few words

There are some important points to remember about VDH:

  • a (ViewDragHelper.Callback) is used as a communication channel between parent view and VDH
  • there is a static factory method to create a VDH instance
  • you can configure the drag direction as you want
  • a drag can be detected from edge even if there is no view to capture (left, right, top, bottom)

Remember to read the official documentation: ViewDragHelper and ViewDragHelper.Callback

Reading the source code

The VDH and its callback are available in the support-v4 library. You can read the source code: ViewDragHelper and ViewDragHelper.Callback.

It uses some common classes of the framework : – a VelocityTracker for>Scroller to scroll views when it’s needed.

You must read the source code as much as possible because first, it’s very interesting and then if you know how it works, you will be able to use it in a better way.

Using the VDH

In this section, I’m going to show you a few examples of what is possible to configure on a VDH. Let’s begin with some initializations and then, I will explain a few possible configurations.

VDH’s initialization

A custom ViewGroup extending a LinearLayout (DragLayout) with a simple child View (named mDragView).

code>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class DragLayout extends LinearLayout {  private final ViewDragHelper mDragHelper; private View mDragView;  public DragLayout(Context context) {  this(context, null); }  public DragLayout(Context context, AttributeSet attrs) {  this(context, attrs, 0); }  public DragLayout(Context context, AttributeSet attrs, int defStyle) {  super(context, attrs, defStyle); } 

你可能感兴趣的:(Each Navigation Drawer Hides a ViewDragHelper)