Android Custom ViewGroup Toggle view with adsorption effect

Source: Internet
Author: User

1. Overview first on

This is probably the effect, first talk about the implementation of ideas 1. First we want to get the URL (network) or ID, path (local) of the image, bind the view to the data, Write our own Adapter2. Customizing the layout of the view to be displayed, and handling touch events for logical processing 3. Write Toggle Callback
2. Implementation 1) custom adapter Here I downloaded the network picture, also can put the picture in res set ImageView content
public class Dragpageviewadapter {private static final String TAG = "Dragpageviewadapter";    Private list<wxcollocationrandomlist> Mdatas;    Private Context Mcontext;    Private Layoutinflater Inflater;    /** * Width and Height */int width;    int height;        Public Dragpageviewadapter (Context mcontext) {this.mcontext = Mcontext;        Inflater = Layoutinflater.from (Mcontext); width = (int) (0.8*dragviewactivity.mscreenwidth); <span style= "font-family:arial, Helvetica, Sans-serif;"    >//width is the 0.8</span> height = (int) (0.8*dragviewactivity.mscreenwidth) of the screen width;    } public int GetCount () {return mdatas==null?0:mdatas.size ();    } public int Getitemid (int position) {return position;    } public Object GetItem (int position) {return mdatas==null?null:mdatas.get (position); Public View GetView (int position, view Convertview, ViewGroup parent) {LOGHELPER.D (TAG, "position:" + positio        n); Final ImageView IMageview = new ImageView (mcontext);        Relativelayout.layoutparams params = new Relativelayout.layoutparams (width,height);        Params.addrule (Gravity.center);        Imageview.setlayoutparams (params);        Imageview.setbackgrounddrawable (Mcontext.getresources (). getdrawable (R.drawable.gray_border));        Viewhelper.setalpha (imageview,1.0f);        String url = mdatas.get (position). Getpictureurl (); if (! Utils.stringisnull (URL)) {url = url.substring (0, Url.lastindexof (".")) + "--300x300.png";//Uilhelpe            R.loadimageurl (URL, imageview,0); Uilhelper.loadimageurl (URL, new Simpleimageloadinglistener () {@Override public void Onloadin                Gcomplete (String Imageuri, view view, Bitmap loadedimage) {imageview.setimagebitmap (loadedimage);        }            });        } Convertview = ImageView; Convertview.settag (Mdatas.get (position));//ViewHolder.mImageView.setImageResource ((Integer) Mdatas.get (position));    return convertview;    } public void SetData (List data) {Mdatas = data;    } private class viewholder{ImageView Mimageview; }}

Through this adapter will need to download the picture Hasty Network, when we need to imageview ourselves to request the download. and bind the data through the Settag method with ImageView 2) custom ViewGroup directly on the code, What we're going to do. A.onmeasure method Measure sub-viewb.onlayout method to the sub-view layout c.ontouchevent handle touch events, up when deciding whether to switch the next view, if not by property animation to restore the state of view d. Binding Toggle The callback E. Remove the current view from the VIEWGRUOP, add a view that needs to be loaded, and assign a switch view to the current view to ensure that no more than the specified number of sub-view in the ViewGroup, not oom
public class Dragpageview extends viewgroup{private static final String TAG = "Dragpageview";    /** * Adapter * */private dragpageviewadapter madapter;    /** * View number */private int one_screen_count = 2;    /** * Screen width and height */private int mscrenwidth;    private int mscreenheight;    /** * The width of the child element */private int mchildwidth;    private int mchildheight;    /** * The index */private int mlastindex of the last picture currently;    /** * the subscript/private int mfirstindex of the current first picture;    /** * Current Display view */private view mfirstview;    /** * before touch x Y */private int mdownx;    private int mdowny;    /** * Current Touch x Y */private int mcurx;    private int Mcury;    public static int mdirection =-1;    public static final int direction_left_to_right = 1;    public static final int direction_right_to_left = 2;    /** * Save View and location key value pair */private map<integer,view> Mviewmap = new Hashmap<integer, view> ();    /** * Maximum rotation angle */private int rotate_degree = 30;    private int child_offset = 10;    /** * Save Callback Interface */private Onimagesavedlistener Monimagesavedlistener; public void Setonimagesavedlistener (Onimagesavedlistener monimagesavedlistener) {This.monimagesavedlistener = MOnI    Magesavedlistener;    } public Dragpageview (context context) {This (context, NULL);    } public Dragpageview (context context, AttributeSet Attrs) {This (context, attrs, 0); } public Dragpageview (context context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, Defstyleatt        R);        Get screen width and height windowmanager WindowManager = (windowmanager) context.getsystemservice (Context.window_service);        Displaymetrics metrics = new Displaymetrics ();        Windowmanager.getdefaultdisplay (). Getmetrics (metrics);        Mscrenwidth = Metrics.widthpixels;    Mscreenheight = Metrics.heightpixels; } @Override protected void onmeasure (int widthmeasureSpec, int heightmeasurespec) {/** * obtains this viewgroup superior container for its recommended width and height, as well as the calculation mode */int widthmode = Meas        Urespec.getmode (WIDTHMEASURESPEC);        int heightmode = Measurespec.getmode (Heightmeasurespec);        int sizewidth = measurespec.getsize (Widthmeasurespec);        int sizeheight = measurespec.getsize (Heightmeasurespec);        All Childview and High Measurechildren (Widthmeasurespec, Heightmeasurespec) were calculated.    Setmeasureddimension (Mscrenwidth, sizeheight); } @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {for (int i = 0; i < get ChildCount ();            i++) {View child = Getchildat (i);            Mchildwidth = Child.getmeasuredwidth ();            Mchildheight = Child.getmeasuredheight ();            int left = getwidth ()/2-mchildwidth/2;            int top = getheight ()/2-MCHILDHEIGHT*2/3;            int right = left + mchildwidth;            int bottom = top + mchildheight;       if (i = = 0)         Child.layout (Left+child_offset, Top+child_offset, Right+child_offset, Bottom+child_offset);        Else Child.layout (left, top, right, bottom);        }} public void Initdatas (Dragpageviewadapter madapter) {this.madapter = Madapter;    Initview (); } @TargetApi (Build.version_codes.        Honeycomb) private void Initview () {removeallviews ();            for (int i = 0; i < One_screen_count; i++) {View view = Madapter.getview (I, NULL, this);        Mviewmap.put (I,view);            The view flashback stored in//mviewmap is added to ViewGroup because ViewGroup index = 0 is at the lowest level for (int j= one_screen_count-1; j>=0;j--) {            AddView (Mviewmap.get (j));            if (j = = 0) {Mfirstview = Mviewmap.get (j);        }} mlastindex = One_screen_count-1;    Mfirstindex = mlastindex-one_screen_count-1; } @TargetApi (Build.version_codes. Honeycomb) @Override Public boolean ontouchevent (Motionevent EVENT) {int focusx = (int) event.getx ();        int focusy = (int) event.gety ();                Switch (event.getaction ()) {case MotionEvent.ACTION_DOWN:mDownX = Mcurx = Focusx;                Mdowny = Mcury = Focusy;            Break                Case MotionEvent.ACTION_MOVE:final int deltax = Focusx-mcurx;                Final int deltay = Focusy-mcury; if (Math.Abs (deltax) > 5 | | Math.Abs (DeltaY) >5) {if (Focusx > Mdownx) {mdirection = Direction_left_to_                    right;                    }else {mdirection = Direction_right_to_left; } handlerscroll (DeltaX, DeltaY);//Mfirstview.setpivotx ((float) (MFIRSTVIEW.GETMEASUREDW                    Idth () *0.5));//Mfirstview.setpivoty (Mfirstview.getmeasuredheight ());                Mfirstview.setrotation (rotate_degree* (FOCUSX-MDOWNX)/mchildwidth);   }             Mcurx = Focusx;                Mcury = Focusy;            Break  Case MOTIONEVENT.ACTION_UP:LOGHELPER.D (TAG, "Mprex:" + mdownx + "Mprey" + Mdowny + "Mcurx:" + Mcurx                + "Mcury:" + Mcury); if (Math.Abs (MCURX-MDOWNX) > Mchildwidth/2 && mlastindex < Madapter.getcount ()) {Loadnext                Image ();                }else {Resetview ();        } break;    } return true;        } private void Resetview () {Propertyvaluesholder oax= propertyvaluesholder.offloat ("Translationx", 0);        Propertyvaluesholder Oay = propertyvaluesholder.offloat ("Translationy", 0);        Propertyvaluesholder rotate = propertyvaluesholder.offloat ("Rotation", 0);    Objectanimator.ofpropertyvaluesholder (Mfirstview, Oax, Oay, rotate). Start ();        } public void Loadnextimage () {objectanimator oax = null;        Objectanimator oarotate = null; if (mlastIndex = = Madapter.getcount ()) return;             if (mdirection = = direction_left_to_right) {oax = new Objectanimator (). Offloat (Mfirstview, "Translationx", 800);            Oarotate = new Objectanimator (). Offloat (Mfirstview, "rotation", rotate_degree); Notifies the callback that the saved view if (Monimagesavedlistener! = null) {monimagesavedlistener.onimagesaved (Mfirstview            );            }}else {oax = new Objectanimator (). Offloat (Mfirstview, "Translationx",-800);            Oarotate = new Objectanimator (). Offloat (Mfirstview, "rotation",-rotate_degree);            if (Monimagesavedlistener! = null) {monimagesavedlistener.onimagedelete (Mfirstview); }} oax.addlistener (new Animatorlisteneradapter () {@Override public void Onanimatione                nd (Animator animation) {//After the end of the animation load the next picture mviewmap.remove (Mfirstindex);   Delete View removeallviews ();             Gets the next picture if ((mlastindex+1) >= Madapter.getcount ()) {AddView (mviewmap.ge                T (Mlastindex));                    }else {View view = Madapter.getview (++mlastindex, NULL, dragpageview.this);                    Mviewmap.put (Mlastindex, view);                    AddView (Mviewmap.get (Mlastindex));                    AddView (Mviewmap.get (mLastIndex-1));                Mfirstview = Mviewmap.get (mLastIndex-1);        }            }        });        Turn on animation Oarotate.start ();    Oax.start (); } @TargetApi (Build.version_codes. Honeycomb) private void handlerscroll (float Distancex, float distancey) {int newleft = (int) (Mfirstview.getlef        T () +distancex);        int newtop = (int) (Mfirstview.gettop () +distancey);        Float[] Deltavector = {Distancex, distancey};        Mfirstview.getmatrix (). Mapvectors (Deltavector);     Mfirstview.settranslationx (Mfirstview.gettranslationx () + deltavector[0]);   Mfirstview.settranslationy (Mfirstview.gettranslationy () + deltavector[1]);        } public interface onimagesavedlistener{public void onimagesaved (view view);    public void Onimagedelete (view view); }}
3) What the activity is responsible for. A. Request data initialization adapter and VIEWGROUPB. The response of the toggle callback C. Event handling with the click of a button toggle
public class Dragviewactivity extends baseactivity{private static final String TAG = "dragviewactivity";    Private Dragpageviewadapter adapter;    Private Dragpageview Mdragview;    private int pageIndex = 1;    private int pageSize = 21;    private int total;    /** * UserID */private String userId;    The data of the network request is private list<wxcollocationrandomlist> lists;    The information of the saved view is private list<wxcollocationrandomlist> msavedview;    Private Wxcollocationrandomlist Mviewinfo;    /** * Screen width and height */public static int mscreenwidth;    public static int mscreenheight;    Private TextView Mskip;    Private TextView Msave;    Private TextView Mdone;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.dragview_act);        WindowManager WindowManager = (windowmanager) getsystemservice (Window_service);        Displaymetrics displaymetrics = new Displaymetrics (); WiNdowmanager.getdefaultdisplay (). Getmetrics (Displaymetrics);        Mscreenwidth = Displaymetrics.widthpixels;        Mscreenheight = Displaymetrics.heightpixels;        UserId = Settingsmanager.getsettingsmanager (this). GetUserId ();        Initview ();    Httpgetimageinfo (PageIndex);        } private void Httpgetimageinfo (final int pageIndex) {Jsonobject object = new Jsonobject ();            try {object.put ("PageIndex", PageIndex);        Object.put ("PageSize", pageSize);        } catch (Jsonexception e) {e.printstacktrace ();        } if (PageIndex = = 1) {showprogress (Getresources (). getString (r.string.app_data_loading)); } httpsrequestutil.dohttpsvolleypost (this, Soaservices.collocation_service, Soamethods.random_colloc                    ATION, Httpsrequestutil.get, Object, new Response.listener<string> () {@Override public void Onresponse (String response) {IF (PageIndex ==1) {closeprogress ();                    } transformdata (response); }}, new Response.errorlistener () {@Override public void Onerrorrespo                    NSE (volleyerror error) {closeprogress ();    }                }); }/** * Requested data, initialization of adapter and initialization of ViewGroup * @param response */private void Transformdata (String response        ) {Gson Gson = new Gson ();        Wxcollocationrandomfilter wxcollocationrandomfilter= Gson.fromjson (response, Wxcollocationrandomfilter.class);        Total = Wxcollocationrandomfilter.gettotal ();        if (total = = 0) return;        Lists = Wxcollocationrandomfilter.getcollocationrandomlists ();        Adapter.setdata (lists);    Mdragview.initdatas (adapter);        } private void Initview () {Mdragview = (Dragpageview) Findviewbyid (R.id.dragview); adapter = new DRagpageviewadapter (this); Mdragview.setonimagesavedlistener (New Dragpageview.onimagesavedlistener () {@Override public void on                Imagesaved (view view) {Mviewinfo = (wxcollocationrandomlist) view.gettag ();            Httpsavefavorite (Mviewinfo); } @Override public void Onimagedelete (view view) {Mviewinfo = (Wxcollocationrandomli                ST) View.gettag ();            Httpdeletefavorite (Mviewinfo);        }        });        Mskip = (TextView) Findviewbyid (R.ID.SKIP);        Msave = (TextView) Findviewbyid (R.id.save);        Mdone = (TextView) Findviewbyid (R.id.done);                Mskip.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Mdragview.mdirection = Mdragview.direction_right_to_left;            Mdragview.loadnextimage ();        }        });            Msave.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {mdragview.mdirection = Mdragview.direction_left_to_right                ;            Mdragview.loadnextimage ();        }        });                Mdone.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            DragViewActivity.this.finish ();    }        }); }/** * like * @param mviewinfo collocation information Source_type 1 Item 2 with */private void Httpsavefavorite (wxcollocation        Randomlist mviewinfo) {jsonobject jsonobject = new Jsonobject ();            try {jsonobject.put ("source_id", Mviewinfo.getid ());            Jsonobject.put ("userid", UserID);            Jsonobject.put ("Create_user", Mviewinfo.getcreateuser ());        Jsonobject.put ("Source_type", 2);        } catch (Jsonexception e) {e.printstacktrace (); } httpsrequestutil.dohttpsvolleypost (Dragviewactivity.this, Soaservices.order_service, SOAMethods.FAVORITE_ADD, Httpsrequestutil.post, Jsonobject, New response.listener<string> () {@Overrid e public void Onresponse (String response) {LOGHELPER.D (TAG, "Savefavorite Succe                    Ss! ");}, new Response.errorlistener () {@Override                    public void Onerrorresponse (Volleyerror error) {LOGHELPER.D (TAG, "Savefavorite error!");    }                }); }/** * Delete like * @param mviewinfo collocation information Source_type 1 Item 2 with */private void Httpdeletefavorite (Wxcolloca        Tionrandomlist mviewinfo) {jsonobject jsonobject = new Jsonobject ();            try {jsonobject.put ("source_id", Mviewinfo.getid ());            Jsonobject.put ("userid", UserID);            Jsonobject.put ("Create_user", Mviewinfo.getcreateuser ());        Jsonobject.put ("Source_type", 2);            } catch (Jsonexception e) {E.printstacktrace (); } httpsrequestutil.dohttpsvolleypost (Dragviewactivity.this, Soaservices.order_service, SOAMethods.FAVORITE_DELETE                    , Httpsrequestutil.post, Jsonobject, New response.listener<string> () {@Override public void Onresponse (String response) {LOGHELPER.D (TAG, "Deletefavorite succes                    S! ");}, new Response.errorlistener () {@Override                    public void Onerrorresponse (Volleyerror error) {LOGHELPER.D (TAG, "Deletefavorite error!");    }                }); }}





The final effect is also good, interested in can study. Demo http://download.csdn.net/detail/hlglinglong/8359097
This article refers to the article: Hung Yang great God Blog
http://blog.csdn.net/lmj623565791/article/details/38140505
http://blog.csdn.net/lmj623565791/article/details/38339817

Android Custom ViewGroup Toggle view with adsorption effect

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.