Android Imitation Takeaway shopping Cart

Source: Internet
Author: User
Tags recyclerview android

Knowledge Point Analysis

To see not complex content and not much, it is worth introducing the knowledge point is the next few
-List title hover
-linkage when the left and right list is sliding
-Parabolic animation when adding a product
-bottom pop up shopping cart list
-Synchronization of data

Another is the realization of the effect of the time may encounter several pits ...

Layout is straightforward to go directly into the code

List title hover

Now do the project list of what basically abandoned the listview instead of Recyclerview, the title hover in the previous blog was also using a Recyclerview open source project sticky-headers-recyclerview , but when writing this demo encountered two pits

    • Sticky-headers-recyclerview the scrolltoposition (int position) method scrolls in an inaccurate position when hovering over a caption.
    • When the layout is complex, if the width of the recyclerview is adaptive or the use of weight percentages may cause the header to appear blank.

and the Open source project author has stopped maintenance, so this time back again StickyListHeadersListView .

Need Shopping Cart Demo is a lot of novice, here is a brief introduction of the use of Stickylistheaderslistview

    • As reference Gradle file added in dependencies
Compile ' se.emilsjolander:stickylistheaders:2.7.0 '
    • Use Stickylistheaderslistview instead of ListView in XML file
      <se.emilsjolander.stickylistheaders.stickylistheaderslistview        android:layout_width= "Match_parent"        Android:background= "#fff"        android:id= "@+id/itemlistview"        android:layout_height= "match_parent" >    </se.emilsjolander.stickylistheaders.StickyListHeadersListView>
    • Adapter inherit Baseadapter and interface Stickylistheadersadapter
The Stickylistheadersadapter interface consists of two methods
View Getheaderview (int position, view Convertview, ViewGroup parent);    Long Getheaderid (int position);

using the same code as the ListView, here are a few unique methods to see the method name is also easy to understand the use of
public void Setareheaderssticky (Boolean areheaderssticky);p ublic boolean areheaderssticky ();p ublic void Setonheaderclicklistener (Onheaderclicklistener Listener);p Ublic interface Onheaderclicklistener {public    void Onheaderclick (stickylistheaderslistview L, View header, int itemposition, Long Headerid, Boolean currentlysticky);} public void Setonstickyheaderchangedlistener (Onstickyheaderchangedlistener listener);p Ublic interface Onstickyheaderchangedlistener {    void onstickyheaderchanged (Stickylistheaderslistview L, View header, int Itemposition, long Headerid);} Public View getlistchildat (int index);p ublic int getlistchildcount ();

Left and right list linkage

Linkage mainly has two effects
-Left list click on select category, right list swipe to corresponding category
-the list on the right of the left list highlights the category following changes during sliding

The first effect is simple, the left list item adds a Click event, and the event calls the setselection (int positon) method of the list on the right.

The second effect adds Scrolllistener to the list on the right and sets the selected category to the left based on the first data shown in the list

Listview.setonscrolllistener (New Abslistview.onscrolllistener () {            @Override public            Void Onscrollstatechanged (abslistview view, int scrollstate) {            }            @Override public            void Onscroll (Abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {            //get the category ID according to Firstvisibleitem, Get the location on the left to be selected according to the category ID                goodsitem item = datalist.get (Firstvisibleitem);                if (Typeadapter.selecttypeid! = Item.typeid) {                    Typeadapter.selecttypeid = Item.typeid;                    Typeadapter.notifydatasetchanged ();                    The list on the left is a recyclerview so use smoothscrolltoposition (int position) so that when the corresponding position item can scroll to show                    rvtype.smoothscrolltoposition (int position) (Getselectedgroupposition (Item.typeid));}}        );
Add an animation for a product

Add a product a total of three animations
-When the product rotates from 0 to 1 the left shift displays the minus button
-When the product from 1 to 0 minus button rotation right moves away
-Add item when parabolic animation is added to Cart icon

The first two animations are simple to break down into three motion tween rotations, panning, and transparency.
Can be done with XML, or code settings, but there is a small pit to note that the rotation animation must be in front of the translation animation, otherwise it is not rolling translation, but jumping ...

Here's how to put the animation code setting

Animation showing minus sign private Animation getshowanimation () {Animationset set = new Animationset (true); Rotateanimation rotate = new Rotateanimation (0,720,rotateanimation.relative_to_self,0.5f,rotateanimation.relative_        to_self,0.5f);        Set.addanimation (rotate);                Translateanimation translate = new Translateanimation (translateanimation.relative_to_self,2f , translateanimation.relative_to_self,0, translateanimation.relative_to_self,0, Translatean Imation.        relative_to_self,0);        Set.addanimation (translate);        Alphaanimation alpha = new alphaanimation (0,1);        Set.addanimation (Alpha);        Set.setduration (500);    return set;        }//Hide the minus sign of the animation private Animation gethiddenanimation () {Animationset set = new Animationset (true); Rotateanimation rotate = new Rotateanimation (0,720,rotateanimation.relative_to_self,0.5f,rotateanimation.relative_        to_self,0.5f); Set.addanimation (rotate);        Translateanimation translate = new Translateanimation (translateanimation.relative_to_self,0 , translateanimation.relative_to_self,2f, translateanimation.relative_to_self,0, Tra        nslateanimation.relative_to_self,0);        Set.addanimation (translate);        Alphaanimation alpha = new Alphaanimation (1,0);        Set.addanimation (Alpha);        Set.setduration (500);    return set;        }//Perform animation simply give the corresponding control setanimation and then call the Setvisibility method {.... tvminus.setanimation (Gethiddenanimation ());    Tvminus.setvisibility (View.gone); }

Parabolic animation and the above can be decomposed into two flat moving pictures, but two flat moving picture of the difference of a linear acceleration only, because the animation interface span is relatively large, it needs to be written in the root, cannot be written in the list of item (this will not show the whole).
The anim_mask_layout in the code is the root layout of the entire layout file, and here is a relativelayout

Implementation process
1, first click on the plus icon, get control on the screen absolute coordinates, callback activity display animation

    int[] loc = new int[2];    V.getlocationinwindow (Loc);    Activity.playanimation (Loc);
2. Create an animated control and add it to the root office and remove the animation view after the animation is finished
public void Playanimation (int[] start_location) {ImageView img = new ImageView (this);        Img.setimageresource (R.drawable.button_add);    Setanim (img,start_location);        }//Create animation translation Animation Direct pass offset private Animation createanim (int startx,int starty) {int[] des = new int[2];        Imgcart.getlocationinwindow (DES);        Animationset set = new Animationset (false);        Animation Translationx = new Translateanimation (0, des[0]-startx, 0, 0);        The linear interpolator defaults to the linear translationx.setinterpolator (new Linearinterpolator ());        Animation translationy = new Translateanimation (0, 0, 0, des[1]-starty);        Set up the accelerator Translationy.setinterpolator (New Accelerateinterpolator ());        Animation alpha = new Alphaanimation (1,0.5f);        Set.addanimation (Translationx);        Set.addanimation (Translationy);        Set.addanimation (Alpha);        Set.setduration (500);    return set; }//Calculate the coordinates of the animation view in the root office add to the root office private void Addviewtoanimlayout (fInal ViewGroup VG, final view view, int[] location) {int x = location[0];        int y = location[1];        int[] loc = new INT[2];        Vg.getlocationinwindow (Loc);        View.setx (x);        View.sety (y-loc[1]);    Vg.addview (view); }//Set animation end remove animation View private void Setanim (Final View V, int[] start_location) {addviewtoanimlayout (anim_mask_        Layout, V, start_location);        Animation set = Createanim (Start_location[0],start_location[1]); Set.setanimationlistener (New Animation.animationlistener () {@Override public void Onanimationstart ( Animation Animation) {} @Override public void Onanimationend (final Animation Animation) {//Direct remove may be error mhanlder.postdelayed (new Runnable () {@Overr) because the interface is still in the drawing                  IDE public void Run () {Anim_mask_layout.removeview (v);  }},100);        } @Override public void Onanimationrepeat (Animation Animation) {}});    V.startanimation (set); }

Bottom pop up shopping cart list

The effect of the bottom pop-up everyone must be very familiar with, a few back every project will be used to, the official did not provide a simple control implementation, generally need to write their own, but to do simple and smooth, easy to transplant recommend the use of third-party library, here to you recommend a

Bottomsheet

Simple integration, diverse effects here is a brief introduction to how to use

    • Integration
Compile ' com.flipboard:bottomsheet-core:1.5.1 '

    • Use

The background layout of the Bottomsheetlayout package pop-up view is used in XML, Bottomsheetlayout inherits from frame layout

<pre name= "code" class= "HTML" ><com.flipboard.bottomsheet.bottomsheetlayout xmlns:android= "/http/ Schemas.android.com/apk/res/android "android:id=" @+id/bottomsheetlayout "android:layout_width=" Match_parent "Android oid:layout_height= "Match_parent" > <linearlayout android:orientation= "Horizontal" Android:layout_wid            Th= "Match_parent" android:layout_height= "match_parent" > <android.support.v7.widget.recyclerview Android:layout_width= "100DP" android:id= "@+id/typerecyclerview" android:layout_height= "Match_pa Rent "> </android.support.v7.widget.RecyclerView> <se.emilsjolander.stickylistheaders.stickylisth Eaderslistview android:layout_width= "match_parent" android:background= "#fff" android:id= " @+id/itemlistview "android:layout_height=" match_parent "> </se.emilsjolander.stickylistheaders.stic Kylistheaderslistview> </linEarlayout></com.flipboard.bottomsheet.bottomsheetlayout> 


Easy to use in your code

    Pop-up View  Bottomsheet is the view    Bottomsheetlayout.showwithsheetview (bottomsheet) to pop up;    Code-behind view (click outside the pop-up view to hide the pop-up view, swipe to slide)    bottomsheetlayout.dismisssheet ();

Synchronization of data

Synchronization of data, control interface refresh should be the easiest place for beginners to detours, in fact, as long as careful is not difficult, here is a simple idea (and not necessarily suitable for your project).

    Commodity list    private arraylist<goodsitem> dataList;    Category List    private arraylist<goodsitem> typelist;    The goods have been selected    private sparsearray<goodsitem> selectedlist;    Used to record the number of each group selection    private Sparseintarray groupselect;

Sparsearray This class is actually hashmap< integer,object >

However, Sparsearray can either find value by key, or find value based on location, performance is higher than HashMap, is the official recommended alternative class,
The same sparseintarray is actually a substitute for hashmap< integer,integer>.

activity implemented the following methods for unified data management &NBSP;
list the number of goods purchased is uniformly obtained from activity, The addition and reduction of goods unified call activity method and then notifidatasetchanged, because the code a lot of specific or look at the source bar

/** * Item represents the purchase quantity of a product plus a * @param item * @param refreshgoodlist whether to refresh the item list */public void Add (Goodsitem it        Em,boolean refreshgoodlist) {int groupcount = Groupselect.get (Item.typeid);        if (groupcount==0) {groupselect.append (item.typeid,1);        }else{groupselect.append (Item.typeid,++groupcount);        } Goodsitem temp = Selectedlist.get (item.id);            if (temp==null) {item.count=1;        Selectedlist.append (Item.id,item);        }else{temp.count++;    } update (refreshgoodlist); }/** * Item purchase quantity minus one * @param item * @param refreshgoodlist whether to refresh item list */public void Remove (GOODSI        TEM item,boolean refreshgoodlist) {int groupcount = Groupselect.get (Item.typeid);        if (groupcount==1) {groupselect.delete (Item.typeid);        }else if (groupcount>1) {groupselect.append (Item.typeid,--GroupCount); } Goodsitem temp = SelectedliSt.get (item.id);            if (temp!=null) {if (temp.count<2) {selectedlist.remove (item.id);            }else{item.count--;    }} update (refreshgoodlist); }/** * Refresh interface Total price, purchase quantity, etc. * @param refreshgoodlist whether to refresh the item list */private void Update (Boolean refreshgoodlist    ){        ...    }        Gets the purchase quantity of the current item according to the item ID public int Getselecteditemcountbyid (int id) {Goodsitem temp = selectedlist.get (ID);        if (temp==null) {return 0;    } return Temp.count;    }//Gets the quantity belonging to the current category according to the category ID public int getselectedgroupcountbytypeid (int typeId) {return groupselect.get (typeId); }

specific logic or look at the code bar, perhaps a more simple implementation ...

Below is the source code: Android Studio Project:http://download.csdn.net/detail/wenwins/9540347


Article reference from:http://blog.csdn.net/w804518214/article/details/51570975


Android Imitation Takeaway shopping Cart

Related Article

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.