Viewdraghelper let you handle view dragging, the code is halved!

Source: Internet
Author: User
Tags gety

Source: Viewdraghelper is a file under the V4 package.

We sometimes get a headache when customizing ViewGroup, and a large part of this is because event handling is too cumbersome, requiring a large number of member variables, a variety of judgments, and so on.
Google also felt the trouble, so Viewdraghelper appeared, Viewdraghelper function in the end what is it? In the literal sense, it is the Help class for view dragging, in short, the amount of code that is simplified when the view is dragged and dragged. Let's take a look at how big this kind of help is.
Let's start with a pull menu effect.

First of all, if we do not use this help class to achieve the situation:
1, rewrite a relativelayout;
2, rewrite the onintercepttouchevent (do the corresponding event interception operation)
2, rewrite the Ontouchevent method (which makes a lot of code)
3, define a scroller variable, to control the operation of the finger release later
I will not write code here, the code must be very large!
Take a look at the code implemented with the Viewdraghelper class

/** * Created by Gyzhong on 15/4/8. * * Public  class VdhLayout01 extends relativelayout {    PrivateViewdraghelper Mviewdraghelper;PrivateView Mcaptureview;Private floatMinitialmotionx;Private floatMinitialmotiony;Private BooleanMisunabletodrag;Private intMsliderange;Private floatMslideoffset; Public VdhLayout01(Context context) { This(Context,NULL); } Public VdhLayout01(context context, AttributeSet attrs) { This(Context, Attrs,0); } Public VdhLayout01(context context, AttributeSet attrs,intDEFSTYLEATTR) {Super(Context, attrs, defstyleattr);    Initview (context); }Private void Initview(Context context) {Mviewdraghelper = Viewdraghelper.create ( This,1.0FNewDraghelpercall ()); }@Override    protected void onfinishinflate() {Super. Onfinishinflate ();        Mcaptureview = Findviewbyid (R.id.id_capture_view);        TextView TextView = (TextView) Findviewbyid (R.id.id_text); Textview.settext (shakespeare.dialogue[0]); }@Override    protected void Onattachedtowindow() {Super. Onattachedtowindow (); Mcaptureview.getviewtreeobserver (). Addonpredrawlistener (NewViewtreeobserver.onpredrawlistener () {@Override             Public Boolean Onpredraw() {mcaptureview.getviewtreeobserver (). Removeonpredrawlistener ( This); Msliderange = Mcaptureview.getmeasuredwidth ();return false;    }        }); }Private  class draghelpercall extends viewdraghelper. Callback {        @Override         Public Boolean Trycaptureview(View Child,intPointerid) {returnChild = = Mcaptureview; }@Override         Public void onviewpositionchanged(View Changedview,intLeftintTopintDxintDY) {Super. onviewpositionchanged (Changedview, left, top, DX, dy); Mslideoffset = left *1.0f/msliderange*2; }@Override         Public int Clampviewpositionhorizontal(View Child,intLeftintDX) {returnClamp (left,0, Msliderange/2); }@Override         Public int Getviewhorizontaldragrange(View Child) {returnmsliderange/2; }@Override         Public void onviewreleased(View Releasedchild,floatXvel,floatYvel) {intFinalleft;if(Xvel >0|| Xvel = =0&& Mslideoffset >. 5f) {finalleft = msliderange/2; }Else{Finalleft =0;            } Mviewdraghelper.settlecapturedviewat (Finalleft, Mcaptureview.gettop ());        Invalidate (); }    }@Override     Public void Computescroll() {if(Mviewdraghelper.continuesettling (true) {Viewcompat.postinvalidateonanimation ( This); }    }Private int Clamp(intValueintMinintMax) {returnMath.min (Max, Math.max (min, value)); }@Override     Public Boolean onintercepttouchevent(Motionevent ev) {Final intAction = motioneventcompat.getactionmasked (EV);if(action = = Motionevent.action_cancel | | action = = MOTIONEVENT.ACTION_UP) {Mviewdraghelper.cancel ();return false; }if(!isenabled () | | (Misunabletodrag && Action! = Motionevent.action_down)) {Mviewdraghelper.cancel ();return Super. onintercepttouchevent (EV); }intindex = motioneventcompat.getactionindex (EV);Switch(action) { CaseMotionevent.action_down: {Final floatx = Ev.getx ();Final floaty = ev.gety ();                Minitialmotionx = x;                Minitialmotiony = y; Misunabletodrag =false; Break; } CaseMotionevent.action_move: {Final floatx = Ev.getx ();Final floaty = ev.gety ();Final floatADX = Math.Abs (X-minitialmotionx);Final floatAdy = Math.Abs (y-minitialmotiony);intSlop = Mviewdraghelper.gettouchslop ();if(ADX > Slop && ADX < Ady) {Misunabletodrag =true; Mviewdraghelper.cancel ();return false; } Break; }        }returnMviewdraghelper.shouldintercepttouchevent (EV); }@Override     Public Boolean ontouchevent(Motionevent event) {mviewdraghelper.processtouchevent (event);return true; }}

As you can see here we are only dealing with event interception, as this involves ScrollView, which is simpler if no event interception is involved! And the most complex ontouchevent method, we did nothing, just let him to Viewdraghelper class to deal with.
If you look at the source of Drawerlayout and slidingpanelayout friends should know that the two controls are using this helper class.
Looking at the effect of Viewdraghelper, let's look at its use,

/** * 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. */

The above paragraph is a description of the Viewdraghelper class. Approximate meaning tell you viewdraghelper is a tool class for custom viewgroup that provides a series of useful operations when we drag or reset a pair of view.
From this paragraph we can know a message, this class is mostly used in custom viewgroup, of course, like the above example, rewrite relativelayout is actually equivalent to custom viewgroup.
The construction method of instantiating Viewdraghelper,viewdraghelper is privatized, so we cannot directly new, need to pass

public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb) {        //...        return helper;}

Or

publicstaticcreate(ViewGroup forParent, Callback cb) {        returnnew ViewDragHelper(forParent.getContext(), forParent, cb);}

To instantiate, this column has three parameters, what is the meaning of each one?
ViewGroup Forparent is our custom viewgroup.
Float sensitivity is a drag-and-drop sensitivity
Callback CB is an abstract class defined in Viewdraghelper, we need to rewrite it in the custom ViewGroup, and the core operation is in the various categories, understand the method in this class, basic grasp the use of this helper.

 Public Static Abstract  class Callback {        //But this method is triggered when the drag state changes, such as: from the beginning can not drag, to drag         Public void onviewdragstatechanged(intState) {}//Key methods: As the name implies, here is a record of some worthwhile changes that can be used to handle other operations, such as changing the background color         Public void onviewpositionchanged(View Changedview,intLeftintTopintDxintDY) {}//This method is seldom used, it has little meaning and can be neglected         Public void onviewcaptured(View Capturedchild,intActivepointerid) {}//Key method, finger loose meeting trigger This method, do the reset operation is implemented in this method         Public void onviewreleased(View Releasedchild,floatXvel,floatYvel) {}//Called when the edge is touched         Public void onedgetouched(intEdgeflags,intPointerid) {}//Edge settings not available,         Public Boolean Onedgelock(intEdgeflags) {return false; }//This method is seldom used         Public void onedgedragstarted(intEdgeflags,intPointerid) {}//New sort of Word view in custom ViewGroup         Public int Getorderedchildindex(intIndex) {returnIndex }//Key method: Set the distance to drag horizontally         Public int Getviewhorizontaldragrange(View Child) {return 0; }//Key method: Set the distance to drag vertically 0 means not to drag         Public int Getviewverticaldragrange(View Child) {return 0; }//Key method: Returns True to indicate that you can drag         Public Abstract Boolean Trycaptureview(View Child,intPointerid);//Key method: reposition horizontally moving position, return left means unrestricted         Public int Clampviewpositionhorizontal(View Child,intLeftintDX) {return 0; }//Key method: Reposition vertically moving position, return top means unrestricted         Public int clampviewpositionvertical(View Child,intTopintDY) {return 0; }}

Look at the above comments, and then look back to see the above example is not very simple.

Summarize:

1, the role of Viewdraghelper is a simplified view drag the Help class
2. Most of viewdraghelper used in custom ViewGroup
3, viewdraghelper through the instantiation

create(ViewGroup forParent, float sensitivity, Callback cb) 

method to create
4. Do not forget to call Shouldintercepttouchevent (EV) in Viewdraghelper in the Onintercepttouchevent method in the custom ViewGroup
In the same ontouchevent (Motionevent event), you need to call
Viewdraghelper.processtouchevent (event);

SOURCE download

Viewdraghelper let you handle view dragging, the code is halved!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.