Cet article partage le code spécifique du panier d'achat d'implémentation Rxjava Retrofit pour la référence de chacun. Le contenu spécifique est le suivant
Image de reproduction:
1. Dépendance
AnnotationProcessor 'com.jakewharton: Butterknife-Compiler: 8.8.1' compile 'com.jakewharton: Butternkife: 8.8.1' compile 'com.android.support:recyclerview-v7:26.0.0-alpha1' compile 'com.squareup.retRofit2: Retrofit: 2.3.0' compile '. 'com.squareup.retrofit2: converter-gson: 2.3.0' compile 'com.facebook.fresco: fresco: 0.12.0' compile 'com.facebook.fresco: Support de base animée: 0.12.0' compile 'com.facebook.fresco: animé-webp: 0.12.0' compile 'com.facebook.fresco: animé-webp: 0.12.0' compile 'com.facebook.fresco: Animated-webp: 0.12.0' Compile 'COM.FaceBook.fresco: Animated-webp: 0.12.0' Compile 'COM.FaceBook.fresco: Animated-webp: 0.12.0' Compile 'COM.FaceBook.fresco: Animated-webp: 0.12.0' Compile ' 'com.facebook.fresco: animé-webp: 0.12.0' compile 'com.facebook.fresco: websupport: 0.12.0' compile 'io.reactivex.rxjava2: rxjava: 2.1.7' compile 'com.squareup.retrofit2: adapter-rxjava2: 2.3.0' compile. 'io.reactivex.rxjava2: rxandroid: 2.0.1' compile 'com.squareup.okhttp3: okhttp: 3.9.0' compile 'com.google.code.gson: gson: 2.8.1'
2. Disposition
1. Additionner Layout Layout_Add_delete
<? xml version = "1.0" Encoding = "utf-8"?> <linearlayout xmlns: android = "http://schemas.android.com/apk/res/android" Android: Layout_Width = "Match_parent" Android: Layout_Height = "match_parent" Android: Orientation = "Horizontal" et poids = "1 <TextView Android: id = "@ + id / txt_delete" Android: Layout_Width = "30DP" Android: Layout_Height = "30DP" Android: Text = "Fonduation" Android: Gravity = "Center" Android: Background = "# 8B948B" /> <EditText Android: id = "@ + id / eT_Number" Android: Layout_Margintop = "2DP" Android: Layout_Width = "50DP" Android: Layout_Height = "30DP" Android: Background = "@ Drawable / Edit" Android: Layout_Weight = "0.00" Android: Gravity = "Center" Android: Text = "1" /> <TextView Android: id = "@ + id / txt_add" Android: Layout_Width = "30DP" Android: Layout_Height = "30DP" Android: Text = "Plus" Android: Gravity = "Center" Android: background = "# 8B948B" /> </ linearlayout>
2. Détails du produit Activité de mise en page_main
<? xml version = "1.0" Encoding = "utf-8"?> <relativelayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: fresco = "http://schemas.android.com/apk/res-auto" Android: LAPE_WIDDTH = " Android: Layout_Height = "Match_parent"> <linearlayout Android: Layout_Width = "Match_parent" Android: Layout_Height = "Match_Parent" Android: Orientation = "Vertical"> <com.facebook.drawee.view.SIMPLEDRAWEEVEVEVEV Android: Layout_Height = "450DP" Fresco: PlanholDeMage = "@ mipmap / ic_launcher" /> <textView Android: id = "@ + id / woods_title" Android: Layout_Width = "wrap_content" Android: Layout_Height = "wrap_content" Android: Layout_Margin = "10DP" et texto C'est à vous Android: textSize = "18DP" /> <TextView Android: Layout_Width = "Wrap_Content" Android: Layout_Height = "Wrap_Content" Android: Layout_Margin = "10DP" Android: Text = "Je suis un marchand Android: Layout_AlignParentBottom = "true" Android: Layout_Width = "Match_parent" Android: Layout_Height = "50DP" Android: Orientation = "Horizontal"> <Button Android: ID = "@ + id / btn_addcart" Androi Android: Layout_Height = "Match_parent" Android: background = "# ffc207" Android: text = "Add to Shopping Cart" /> <Button Android: id = "@ + id / btn_shopping" Android: Layout_weight = "1" Android: Layout_Width = "0dp" Android: Layout_Height = "Match_parent" et fond: "FF6B06" Android: text = "acheter maintenant" /> </ linearlayout> </ relativeLayout>
3. Activité de mise en page du panier_main2
<? xml version = "1.0" Encoding = "UTF-8"?> <linearlayout xmlns: android = "http://schemas.android.com/apk/res/android" Android: Layout_Width = "Match_parent" Android: Layout_Height = "Match_parent" Android: Orientation = "Vertical"> <! Android: id = "@ + id / top_bar" Android: Layout_Width = "Match_parent" Android: Layout_Height = "48DP" Android: background = "# f7f7f7" Android: orientation = "Vertical"> <relativelayout Android: Layout_Width = "match_parent" Android: Layout_Height = "48DP" Background = "@ Android: Color / Transparent" Android: Orientation = "Vertical"> <ImageView Android: id = "@ + id / back" Android: Layout_Width = "48DP" Android: Layout_Height = "48DP" Android: LAYOT_ALIGNPARETLEFT = "True" Android: SayoT_Gravity = " Android: src = "@ drawable / back" /> <textView Android: Layout_Width = "Match_parent" Android: Layout_Height = "Wrap_Content" Android: Gravity = "Center" Android: MinHeight = "48DP" Android: Text = "CART SHOP Android: id = "@ + id / edit" Android: Layout_Width = "wrap_content" Android: Layout_Height = "Wrap_Content" Android: Layout_AlignParentRight = "True" Android: Layout_MarginRight = "40DP" Android: Text = "EDIT" Android: textColor = "# 1A1A1A" Android: textSize = "14sp" Android: Visibility = "Visible" /> </ RelativeLayout> </ linearlayout> <ExpandableListView Android: id = "@ + id / exlistView" Android: Layout_Width = "Match_Parent" Android: Layout_Height = "0DP" et comploter "Android =" Layout_Height = "0DP" et complexe: "Android =" Layout_Height = "0DP" et basculer: "Android =" Layout_Height = "0DP" et basculer: "Android =" Layout_Height = "0DP" ANDROID: LA VERRÈSE) Android: childindicator = "@ null" Android: GroupIndicator = "@ null"> </ ExpandableListView> <linearlayout Android: Layout_Width = "Match_parent" Android: Layout_Height = "50DP" Android: Gravity = "Center_Vertical: Android: orientation =" Horizontal "> <Checkbox android: Android: Layout_Marginleft = "20DP" Android: Layout_Width = "Wrap_Content" Android: Layout_Height = "Wrap_Content" /> <TextView Android: Layout_Width = "Wrap_Content" Android: Layout_Height = "Wrap_Content" Android: Text = "SELECT ALL" /> <LINEARLAYOUTOUTOUT Android: id = "@ + id / ll_info" Android: Layout_Width = "0DP" Android: Layout_Height = "Wrap_Content" Android: Layout_Weight = "4"> <linearlayout Android: Layout_Width = "Match_Parent" Android " Android: Layout_MarginRight = "20DP" Android: Layout_Weight = "1"> <linearLayout Android: Layout_Width = "Match_parent" Android: Layout_Height = "Wrap_Content" Android: orientation = "Horizontal" Android: Gravity = "Right"> <TextView Android: Layout_Width = "Wrapent" Android: Layout_Height = "Wrap_Content" Android: Layout_Marginleft = "5DP" Android: Text = "Total:" Android: TextSize = "18SP" Android: TextStyle = "Bold" /> <TextView Android: id = "@ + id / total_price" Android: SOMET_WIDTH = "WINE_CONTENT" Android: text = "¥ 0,00" Android: textColor = "# f23232" Android: textSize = "16Sp" Android: TextStyle = "Bold" /> </ linearlayout> <TextView Android: id = "@ + id / total_number" Produits: 0 pièces "Android: Gravity =" Right "Android: textSize =" 16SP "Android: TextStyle =" Bold "/> </ linearLayout> <TextView Android: id =" @ + id / tv_go_to_pay "Android: Layout_Width =" Match_parent "Android: LAYOUT_HEAG Android: background = "# fd7a05" Android: clickable = "true" Android: Gravity = "Center" Android: Text = "Clear" Android: TextColor = "# Fafafa" /> <TextView Android: ID = "@ + id / tv_go_to_del" Android: Layout_width = "Match_Parent" Android: Layout_Height = "Match_parent" Android: Layout_weight = "3" Android: background = "# e2231c" Android: clickable = "true" Android: Gravity = "Center" Android: Text = "Delete" Android: TextColor = "# FAFAFA" Android: Visibility = "Gone" /> </ linearLayout> </ linearlayout> </ linearlayout>
4. LISTE DE LISTE SECONDAIRE LIGNE DE LISTE EX_GROUP_ITEM
<? xml version = "1.0" Encoding = "utf-8"?> <linearlayout xmlns: android = "http://schemas.android.com/apk/res/android" Android: Layout_Width = "Match_Parent" Android: Layout_Height = "match_parent" Android: background = "# # cfc3" " Android: orientation = "horizontal"> <Checkbox Android: id = "@ + id / group_checkbox" Android: Layout_marginleft = "20dp" Android: Layout_Width = "wrap_content" Android: Layout_Height = "Wrap_Content" Android: Focusable = "false" /> <textView Android: ID = "@ + id / shop_name" Android: Layout_Marginleft = "20DP" Android: Layout_Width = "Wrap_Content" Android: Layout_Height = "Wrap_Content" Android: TextSize = "16DP" /> </ linearlayout>
5. Liste secondaire Sous-Layout ex_child_item
<? xml version = "1.0" Encoding = "utf-8"?> <linearlayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: app = "http://schemas.android.com/apk/res-auto" xmlns: fresco = "http://schemas.android.com/apk/res-auto" Android: Layout_Width = "Match_parent" Android: Layout_Height = "230DP" Android: orientation = "Horizontal"> <cockerbox Android: id = "id / child_checkbox" Android: SHAYOUT_ Android: Layout_Marginleft = "20DP" Android: Layout_MarginBottom = "50DP" Android: Layout_Width = "Wrap_Content" Android: Layout_Harginleft = "20DP" Android: Layout_Width = "Matchginleft" Android: Layout_Height = "Match_parent"> <TextView Android: id = "@ + id / shop_title" Android: Layout_Width = "Wrap_Content" Android: Layout_Height = "Wrap_Content" Android: Layout_AlignParentleft = "True" Androile: Lowout_alignaRentStart = "true" androïde: lameout_Marginlefleft = " Android: Layout_MarginStart = "17DP" Android: Text = "TextView" Android: Layout_AlignParentTop = "True" /> <! - <ImageView Android: ID = "@ + id / shop_img" Android: Layout_Width = "90DP" App: srcCompat = "@ mipmap / ic_launcher" Android: Layout_Below = "@ + id / shop_name" Android: Layout_AlignParentleft = "true" Android: Layout_alignParentStart = "True" /> -> <com.facebook.DRAWE.VIED.SimpledRaweeView Android: id = "@ + id / shop Android: Layout_Width = "90DP" Android: Layout_Height = "90DP" Android: Layout_Margintop = "30DP" FRESCO: PLACEHOLOLDIMAGE = "@ mipmap / ic_launcher" Android: Layout_Below = "TRUE" Android: Layout_AlignParentStart = "true" /> <TextView Android: id = "@ + id / shop_price" Android: Layout_Width = "Wrap_Content" Android: Layout_Height = "Wrap_Content" Android: Layout_alignntop = "@ + id / shop_img" Android: Layout_CenterHorizontal = "True" Android: Layout_Margintop = "10DP" Android: Text = "¥ 20" Android: TextColor = "# F23232" /> <com.bwei.gepeng.myview.adddeleView Android: id = "@ + id / adv" Android: Layout_Width = "160dp" Android: Layout_Height = "30DP" Android: Layout_Below = "@ + id / shop_price" Android: Layout_Margintop = "30DP" Android: Layout_Marginleft = "140dp" App: Left_text = "-" App: droite_text = "+" App: Middle_text = "1" Android: focalable = "false"> </come.bwei.gePeng.MyView.adDDDDDDDDDDDDDDDDDEVEVEVE Android: id = "@ + id / shop_delete" Android: Layout_Width = "wrap_content" Android: Layout_Height = "Wrap_Content" Android: Layout_AlignParetentend = "True" Android: Layout_AlignParentRight = "True" Android: Layout_Centervertic </ RelativeLayout> </ linearlayout>
3. Classe d'entité
1. MessageBean
Package com.bwei.gepeng.entity; classe publique MessageBean <T> {Code de chaîne privée; données t privées; String privé msg; Vendeur de vendeur privé; public String getcode () {return code; } public void setCode (String code) {this.code = code; } public t getData () {return data; } public void setData (t data) {this.data = data; } public String getmsg () {return msg; } public void setmsg (String msg) {this.msg = msg; } public SellerBean getseller () {return vendeur; } public void SetSeller (vendeur vendeur) {this.seller = vendeur; } Classe statique publique SellerBean {/ ** * Description: Je suis un marchand 19 * icon: http://120.27.23.105/images/icon.png * Nom: Merchant 19 * Productnums: 999 * Score: 5.0 * Sellerid: 19 * / Private String Description; Icône de chaîne privée; nom de chaîne privé; Private Int Productnums; double score privé; private int Sellerid; public String getDescription () {return Description; } public void setDescription (String Description) {this.description = Description; } public String genicon () {return icon; } public void seticon (icône de chaîne) {this.icon = icon; } public String getName () {Nom de retour; } public void setName (string name) {this.name = name; } public int getProductNums () {return productNums; } public void setProductNums (int productNums) {this.productNums = productNums; } public double getScore () {return score; } public void setScore (double score) {this.score = score; } public int getSellerid () {return Sellerid; } public void SetSellerid (int Sellerid) {this.sellerid = seleDid; }}}2.BOODSSHOWBEAN
Package com.bwei.gepeng.entity; classe publique GoodshowBean {private double bargainprice; Création de chaîne privée; DetailUrl de chaîne privée; images de chaîne privées; INT PRIVATE ITEMTYPE; Int Pid privé; double prix privé; Int privé PSCID; private int SalesNum; private int Sellerid; Sous-tête de chaîne privée; titre de chaîne privée; public double getBargainPrice () {return BargainPrice; } public void setBargainPrice (double bargainprice) {this.bargainprice = bargainprice; } public String getCreateTime () {return CreateTime; } public void SetCreateTime (String CreateEtime) {this.createTime = CreateTime; } public String getDetailUrl () {return DetailUrl; } public void setDetailUrl (String DetailUrl) {this.detailUrl = DetailUrl; } public String getImages () {return images; } public void setimages (chaîne images) {this.images = images; } public int getItemType () {return itemType; } public void SetItemType (int itemType) {this.itemtype = itemType; } public int getpid () {return pid; } public void setPid (int pid) {this.pid = pid; } public double getPrice () {prix de retour; } public void setPrice (double prix) {this.price = prix; } public int getpscid () {return pscid; } public void setpscid (int pscid) {this.pscid = pscid; } public int getSalenum () {return SalesNum; } public void setsalenum (int vendenum) {this.salenum = vendenum; } public int getSellerid () {return Sellerid; } public void SetSellerid (int Sellerid) {this.sellerid = seleDid; } public String getSubhead () {return subhead; } public void setSubhead (String Subhead) {this.subhead = sous-ivale; } public String getTitle () {return title; } public void SettItle (String Title) {this.title = title; } @Override public String toString () {return "goodshowbean {" + "BargainPrice =" + BargainPrice + ", CreateTime = '" + CreateTime +' / '' + ", de détail = '" + DetailUrl +' / '' + ", images = '" + images +' / '+ ", itemtype =" + Price = "+ Price +", PSCID = "+ PSCID +", SalesNum = "+ SalesNum +", Sellerid = "+ Sellerid +", sous-ivaleur = '"+ sous-idiot +' / '' +", title = '"+ title +' / '' + '}'; }}3. Cartbean
Package com.bwei.gepeng.entity; Importer java.util.list; classe publique CartBean {private String sellname; STRACHE PRIVÉE VERLERID; Liste privée <SistBean> Liste; public String getELLERNAME () {return sellName; } public void SetSeLername (String sellName) {this.sellername = sellName; } public String getSellerid () {return Sellerid; } public void SetSellerid (String Sellerid) {this.sellerid = Sellerid; } public List <SistBean> getList () {return list; } public void setList (list <s listBean> list) {this.list = list; } public static class listBean {private double bargainprice; Création de chaîne privée; DetailUrl de chaîne privée; images de chaîne privées; int privé int num; Int Pid privé; double prix privé; Int privé PSCID; private int sélectionné; private int Sellerid; Sous-tête de chaîne privée; titre de chaîne privée; public double getBargainPrice () {return BargainPrice; } public void setBargainPrice (double bargainprice) {this.bargainprice = bargainprice; } public String getCreateTime () {return CreateTime; } public void SetCreateTime (String CreateEtime) {this.createTime = CreateTime; } public String getDetailUrl () {return DetailUrl; } public void setDetailUrl (String DetailUrl) {this.detailUrl = DetailUrl; } public String getImages () {return images; } public void setimages (chaîne images) {this.images = images; } public int getnum () {return num; } public void setNum (int num) {this.num = num; } public int getpid () {return pid; } public void setPid (int pid) {this.pid = pid; } public double getPrice () {prix de retour; } public void setPrice (double prix) {this.price = prix; } public int getpscid () {return pscid; } public void setpscid (int pscid) {this.pscid = pscid; } public int getSelected () {return sélectionné; } public void setSelected (int selected) {this.selected = selected; } public int getSelerid () {return Sellerid; } public void SetSellerid (int Sellerid) {this.sellerid = seleDid; } public String getSubhead () {return subhead; } public void setSubhead (String Subhead) {this.subhead = sous-ivale; } public String getTitle () {return title; } public void SettItle (String Title) {this.title = title; }} @Override public String toString () {return "CartBean {" + "sellName = '" + sellName +' / '' + ", seled = '" + venderid +' / '' + ", list =" + list + '}'; }}4. GroupBean
Package com.bwei.gepeng.entity; classe publique GroupBean {private String sellname; Groupe booléen privé; public GroupBean (String sellName, boolean groupUCB) {this.sellername = sellname; this.gropUCB = groupecb; } public String getELLERNAME () {return sellName; } public void SetSeLername (String sellName) {this.sellername = sellName; } public boolean isGropucb () {return groupUCB; } public void setGropUCB (boolean groupUCB) {this.gropucb = groupecb; } @Override public String toString () {return "GroupBean {" + "sellName = '" + sellName +' / '' + ", groupUCB =" + groupecb + '}'; }}5.ChildBean
Package com.bwei.gepeng.entity; classe publique Childbean {Titre de la chaîne privée; images de chaîne privées; double prix privé; int privé int num; Boolean ChildCB privé; Boolean privé BTN; Int Pid privé; Public Childbean (titre de chaîne, images de chaîne, double prix, int num, boolean childcb, booléen btn, int pid) {this.title = title; this.images = images; this.price = prix; this.num = num; this.childcb = childcb; this.btn = btn; this.pid = pid; } public int getpid () {return pid; } public void setPid (int pid) {this.pid = pid; } public boolean isBtn () {return btn; } public void setBtn (boolean btn) {this.btn = btn; } public String getTitle () {return title; } public void SettItle (String Title) {this.title = title; } public String getImages () {return images; } public void setimages (chaîne images) {this.images = images; } public double getPrice () {prix de retour; } public void setPrice (double prix) {this.price = prix; } public int getnum () {return num; } public void setNum (int num) {this.num = num; } public boolean ischildcb () {return childcb; } public void setchildcb (boolean childcb) {this.childcb = childcb; } @Override public String toString () {return "childbean {" + "title = '" + title +' / '' + ", images = '" + images +' / '' + ", prix =" + prix + ", num =" num + ", childcb =" + childcb + ", btn =" + btn + ", pid =" + pid + '}';;; }}4. Interface
1.Aureur
Package com.bwei.gepeng.http; import com.bwei.gepeng.entity.cartbean; import com.bwei.gepeng.entity.goodshowbean; import com.bwei.gepeng.entity.MessageBean; Importer java.util.list; importation java.util.map; import io.reactivex.flowable; Importer rétriers2.http.get; Importer rétriers2.http.QueryMap; Interface publique APISERVICE {// Détails du produit de requête 75 //http://120.27.23.105/product/getproductdetail?pid=75&source=Android @get ("Product / GetProductDetail") Flowable <MessageBean <String>; // Query Shopping Cart // http: //120.27.23.105/product/getcarts? Uid = 3802 & source = Android @get ("Product / GetCarts") Flowable <MessageBean <list <Cartbean>>> GetCart (@QueryMap Map <String, String> map); // supprimer le panier d'achat // http: //120.27.23.105/product/getCarts? Uid = 3802 & source = Android @get ("Product / Deletecart") Flowable <MessageBean <list <Cartbean>>> getDel (@QueryMap Map <string, string> map); // Ajouter un panier d'achat // http: //120.27.23.105/product/addcart? Uid = 3802 & pid = 75 & source = Android @get ("product / addcart") Flowable <MessageBean <list <CartBean >>> getAdd (@QueryMap Map <String, String> Map); } 2.IVIEW [Java] Voir l'interface Copypublic Plain IView {void onSuccess (objet O, String Tag); void onfailed (exception e, string tag); } 3.Ipresenter [Java] Voir le CopyImport ordinaire java.util.map; Interface publique iPresenter {void getData (map <string, string> map, string tag); } 4.Imodel [java] Voir le CopyImport Plain CopyImport Java.util.map; Interface publique imodel {void getData (map <string, string> map, string tag); }5. Code
1. Affichage personnalisé AdddeleTeview
Package com.bwei.gepeng.myview; import Android.Content.Context; import android.content.res.typedArray; import android.graphics.color; import android.util.attributeset; import Android.view.view; import Android.Widget.EditText; import Android.Widget.LinearLayout; import Android.Widget.TextView; import com.bwei.gepeng.r; La classe publique AdddeleTeview étend LinearLayout {Private OnAddDelClickListener Écouteur; EditText privé Etnumber; // Fournit une interface de rappel de clic pour l'interface publique à usage externe surddDelClickListener {void onAddClick (View v); void ondelClick (View V); } public void setonAddDelClickListener (onaddDelClickListener Écouteur) {if (écouteur! = null) {this.Listener = écouteur; }} public addDeleView (contexte de contexte) {this (context, null); } public adddeleTeview (contexte de contexte, attributeSet attrs) {this (context, attrs, 0); } public adddeleTeview (contexte de contexte, attributeSet attrs, int defStyleattr) {super (contexte, attrs, defstyeattr); initView (context, attrs, Defstyeattr); } private void initView (contexte contextuel, attributeSet attrs, int defstyeattr) {View.inflate (contexte, r.layout.layout_add_delete, this); // Obtenez le contrôle TextView txtDelete = findViewByid (r.id.txt_delete); TextView txtAdd = findViewByid (r.id.txt_add); etNumber = findViewByid (r.id.et_number); TypedArray TypedArray = context.ObtainStyleDattraButes (Attrs, R.Styable.AdddeleEViewStyle); String LeftText = TypedArray.getString (r.styable.adddeleViewStyle_left_text); String RightText = typedArray.getString (r.styable.adddeleViewStyle_Right_text); String MiddleText = TypedArray.getString (R.Styable.AdddeleViewstyle_middle_text); int color = typedArray.getColor (r.styable.adddeleViewstyle_left_text_color, colore.red); txtDelete.SeTText (LeftText); txtAdd.SeTText (RightText); Etnumber.SeTText (MiddleText); txtDelete.seTTextColor (couleur); // Recycler TypedArray.Recycle (); txtdelete.setOnClickListener (new onClickListener () {@Override public void onClick (View View) {LIVERNER.ONDELCLICK (VIEW);}}); txtAdd.setOnClickListener (new onClickListener () {@Override public void onClick (View View) {auditeur.onaddclick (vue);}}); } // Fournit une méthode externe pour modifier les nombres publics void setNumber (int }} // Fournit une méthode externe pour obtenir le numéro actuel public int GetNumber () {String String = EtNumber.getText (). ToString (); int i = Integer.ParseInt (String); retour i; }} 2. Rétrofice des classes d'outils Rétrofitiles
Package com.bwei.gepeng.http; Importer java.io.ioException; import okhttp3.httpurl; import okhttp3.interceptor; import okhttp3.okhttpclient; import okhttp3.request; import okhttp3.Response; Import rétriers2.Rettrofit; Importer rétrie.Adapter.rxjava2.rxjava2CalladapterFactory; Importer rétrie.Converter.gson.gsonConverterFactory; Classe publique Rétrofitutiles {instance de rétrofitutils volatile statique privée; Modification finale privée Rétrofice; Private RetroFitUtiles () {OKHTTPClient client = new OKHTTPCLIENT.BUILDER (). AddInterceptor (new Logger ()). Build (); Retrofit = new RESTOFIT.BUILDER (). Client (Client) .AddCalladapterFactory (RXJava2CalladapterFactory.create ()) .AddConverterFactory (GSONConverterFactory.Create ()) .Baseurl ("http://120.27.23.105/"). } public static rétrofiTUTILS getInstance () {if (instance == null) {synchronisé (rétrofitutils.class) {if (instance == null) {instance = new RetrofiTUtils (); }}} Instance de retour; } public APIService getAPiService () {apiService apiseRvice = restrofit.create (apiService.class); RETOUR APISERVICE; } Class Logger implémente Interceptor {@Override Public Response Intercept (chaîne chaîne) lève ioException {request original = chain.request (); Httpurl url = original.url (). Newbuilder () .addQueryParameter ("source", "android") .build (); // Ajouter une demande de demande de demande = original.newbuilder () .url (url) .build (); retour chain.proceed (demande); }}} 3.M Couche
Package com.bwei.gepeng.model; import com.bwei.gepeng.entity.cartbean; import com.bwei.gepeng.entity.goodshowbean; import com.bwei.gepeng.entity.MessageBean; import com.bwei.gepeng.http.retrofitUtils; import com.bwei.gepeng.presenter.newspresenter; Importer java.util.list; importation java.util.map; import io.reactivex.flowable; Le modèle de classe publique implémente IMODEL {Private Newspresenter Présentateur; Modèle public (présentateur Newspresenter) {this.presenter = présentateur; } @Override public void getData (map <string, string> map, string tag) {if (tag.equals ("cart")) {flowable <MessageBean <list <cartbean >>> flowable = restrofitUtils.getInstance (). Getapiservice (). GetCart (map); présentateur.get2 (flowable, tag); } else if (tag.equals ("marchandises")) {Flowable <MessageBean <GoodshowBean >> Flowable = RetrofiTUtils.getInstance (). getApiService (). getNews (map); présentateur.get (flowable, tag); } else if (tag.equals ("del")) {Flowable <MessageBean <list <CartBean>>> Flowable = RetroFitUtils.getInstance (). getapiService (). GetDel (map); présentateur.get3 (flowable, tag); } else if (tag.equals ("add")) {Flowable <MessageBean <list <CartBean>>> Flowable = RetroFitUtils.getInstance (). getApiService (). GetAdd (map); présentateur.get4 (flowable, tag); }}} 4.Pyer
Package com.bwei.gepeng.presenter; import com.bwei.gepeng.entity.cartbean; import com.bwei.gepeng.entity.goodshowbean; import com.bwei.gepeng.entity.MessageBean; Importer com.bwei.gepeng.model.model; Importer com.bwei.gepeng.view.iview; Importer java.util.list; importation java.util.map; import io.reactivex.flowable; import io.reactivex.android.schedulers.androïdesCedulers; import io.reactivex.schedulers.schedulers; import io.reactivex.subscrirs.DisposablesBscriber; classe publique Newspresenter implémente iPresenter {private iView iView; DisposablesBscribers privés <MessageBean <GoodshowBean >> abonné; DisposablesBscriber privé <MessageBean <list <Cartbean >>> abonné sous 2; DisposablesBscriber privé <MessageBean <list <Cartbean >>> abonné Abonné3; DisposablesBscriber privé <MessageBean <list <Cartbean >>> abonné 4; public void attachView (iView iView) {this.iview = iView; } @Override public void getData (map <string, string> map, string tag) {modèle modèle = nouveau modèle (this); Model.getData (carte, balise); } public void detachview () {if (iView! = null) {iView = null; } if (abonné! = null) {if (! abonné.isdisposed ()) {abonné.dispose (); }} if (abonné 2! = null) {if (! subscnumber2.isDisposed ()) {subsrocber2.dispose (); }} if (abonné3! = null) {if (! subscriber3.isDisposed ()) {subsrocber.dispose (); }} if (abonné 4! = null) {if (! subscriber4.isDisposed ()) {subsrocber4.dispose (); }}} // CART DE RESTION CART PUBLIC VOID GET (FLOWable <MessageBean <GoodshowBean>> Flowable, Final String Tag) {abonné = Flowable.SubScribeon (Schedulers.io ()) .ObServeon (AndRoidsCheDulers.MainThread ()) .SubScribewith (New DisposableBscriber <MessageBean <). public void onNext (MessageBean <biens @Override public void onComplete () {}}); } // requête Détails du produit75 public void get2 (flowable <messageBean <list <cartbean>>> flowable, final string tag) {subsrocbirt2 = flowable.subscribeon (schedulers.io ()) .obServeO @Override public void onNext (messageBean <list <Cartbean >>> list) {if (list! = Null) {list <Cartbean> data = list.getData (); Exception (t), tag);} @Override public void onComplete () {}}); } // Supprimer le panier public VOID GET3 (Flowable <MessageBean <List <Cartbean>>> Flowable, Final String Tag) {subSrocber3 = Flowable.SubScribeon (Schedulers.io ()) .ObServeO public void onNext (MessageBean <list <cartBean >> list) {if (list! = null) {String code = list.getmsg (); }); } // Ajouter un panier public void get4 (flowable <messageBean <list <Cartbean>>> flowable, final string tag) {subsrocber4 = flowable.subscribeon (schedulers.io ()) .obServeon (AndRoidschedulers.MainThread ()) .SubScribewith (@roverRideBScriber <MessageBean <list <CARTBEAN>>) void onNext (MessageBean <list <cartBean >>> list) {if (list! = null) {String code = list.getmsg (); }); }} 5. Page des détails du produit MainActivity
Package com.bwei.gepeng.view; import android.content.intent; import android.os.bundle; import android.support.v7.app.appCompatActivity; import Android.view.view; import Android.Widget.TextView; import android.widget.toast; import com.bwei.gepeng.r; import com.bwei.gepeng.entity.goodshowbean; import com.bwei.gepeng.presenter.newspresenter; Importer com.facebook.drawee.view.simpledRaweeView; import java.util.hashmap; importation java.util.map; Importer Butterknife.bindview; Importer Butterknife.ButterKnife; Importer Butterknife.onclick; La classe publique MainActivity étend AppCompatActivity implémente iView {@bindView (r.id.my_image_view) SimpleDraweeView MyImageView; @BindView (r.id.goods_title) TextView Goodstitle; @Bindview (r.id.goods_price) TextView GoodsPrice; Présentateur privé de Newspresenter; @Override Protected void onCreate (bundle SavedInStanceState) {super.onCreate (SavedInStanceState); setContentView (r.layout.activity_main); Butterknife.bind (ceci); présentateur = new Newspresenter (); présentateur.AttachView (this); //http://120.27.23.105/product/getproductdetail?pid=75&source=Android map <string, string> map = new hashmap <> (); map.put ("pid", "75"); présentateur.getData (carte, "biens"); } @Override public void onSuccess (objet o, string tag) {if (tag.equals ("goods")) {if (o! = Null) {bourseShowBean data = (woodshowbean) o; //Log.e("gp "," onSuccess: "+ data.toString ()); MyImageView.SetImageUri (data.getImages (). Split ("// |") [0]); goodstitle.setText (data.getTitle ()); boursier.SeTTEXT ("¥" + data.getPrice ()); }} else if (tag.equals ("add")) {if (o! = null) {String msg = (string) o; Toast.makeText (mainactivity.Te, msg, toast.length_short) .show (); }}} @Override public void onFailed (exception e, string tag) {} @onclick ({r.id.btn_addcart, r.id.btn_shopping}) public void onviewClicked (vue vue) {switch (voir.getid ()) {case r.id.btn_addcart: map <string, string, map = new hashmap <); map.put ("uid", "3802"); map.put ("pid", "75"); présentateur.getData (map, "ajouter"); //Toast.makeText(mainActivity.This ,"add avec succès ", toast.length_short) .show (); casser; cas r.id.btn_shopping: intention intention = new intention (mainactivity.this, main2activity.class); startActivity (intention); casser; }}} 6. Adaptateur de liste secondaire ExpandableAdapter
Package com.bwei.gepeng.adapter; import Android.Content.Context; import Android.view.view; import Android.view.ViewGroup; import android.widget.baseexpandableListAdapter; import android.widget.button; import Android.Widget.CheckBox; import Android.Widget.TextView; import android.widget.toast; import com.bwei.gepeng.r; import com.bwei.gepeng.entity.ChildBean; import com.bwei.gepeng.entity.GroupBean; import com.bwei.gepeng.myview.AddDeleteView; import com.bwei.gepeng.view.Main2Activity; import com.facebook.drawee.view.SimpleDraweeView; import java.util.ArrayList; import java.util.List; public class ExpandableAdapter extends BaseExpandableListAdapter { private Context context; private List<GroupBean> groupBeen=new ArrayList<>(); private List<List<ChildBean>> childBeen=new ArrayList<>(); private Main2Activity main; public ExpandableAdapter(Context context, List<GroupBean> groupBeen, List<List<ChildBean>> childBeen) { this.context = context; this.groupBeen = groupBeen; this.childBeen = childBeen; this.main = (Main2Activity) context; } //Interface callback private onDeleteGoods onDleGoods; public interface onDeleteGoods{ void onDelGoods(int i,int i1,String pid); } public void setOnDeleteGoods(onDeleteGoods onDleGoods){ this.onDleGoods=onDleGoods; } @Override public int getGroupCount() { return groupBeen.size(); } @Override public int getChildrenCount(int i) { return childBeen.get(i).size(); } @Override public Object getGroup(int i) { return groupBeen.get(i).getSellerName(); } @Override public Object getChild(int i, int i1) { return childBeen.get(i).get(i1).getTitle(); } @Override public long getGroupId(int i) { return i; } @Override public long getChildId(int i, int i1) { return i1; } @Override public boolean hasStableIds() { return false; } //Level 1 group @Override public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) { //Load view view=View.inflate(context, R.layout.ex_group_item ,null); final CheckBox groupCb= view.findViewById(R.id.group_checkbox); TextView shopName= view.findViewById(R.id.shop_name); shopName.setText(groupBeen.get(i).getSellerName()); groupCb.setChecked(groupBeen.get(i).isGropuCb()); //Group check button groupCb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean gchecked = groupCb.isChecked(); groupBeen.get(i).setGropuCb(gchecked); //Main2Activity main= (Main2Activity) context; for(GroupBean i: groupBeen){ boolean groupCb = i.isGropuCb(); if(!groupCb){ main.allCheckbox.setChecked(false); break; }else{ main.allCheckbox.setChecked(true); } } int size = childBeen.get(i).size(); if(gchecked){ for(int r=0;r<size;r++){ //Toast.makeText(context,"group button"+gchecked+""+size, Toast.LENGTH_SHORT).show(); childBeen.get(i).get(r).setChildCb(true); } }else{ for(int r=0;r<size;r++){ //Toast.makeText(context,"group button"+gchecked+""+size, Toast.LENGTH_SHORT).show(); childBeen.get(i).get(r).setChildCb(false); } } notifyDataSetChanged(); main.changesum(childBeen); } }); return view; } //Second-level group @Override public View getChildView(final int i, final int i1, boolean b, View v, ViewGroup viewGroup) { //Load view v=View.inflate(context, R.layout.ex_child_item ,null); final CheckBox childCb = v.findViewById(R.id.child_checkbox); TextView shopTitle= v.findViewById(R.id.shop_title); TextView shopPrice= v.findViewById(R.id.shop_price); //ImageView shopImg=v.findViewById(R.id.shop_img); //draweeView.setImageURI(uri); SimpleDraweeView shopImg = v.findViewById(R.id.shop_img); final AddDeleteView adv = v.findViewById(R.id.adv); Button shop_delete=v.findViewById(R.id.shop_delete); childCb.setChecked(childBeen.get(i).get(i1).isChildCb()); String images = childBeen.get(i).get(i1).getImages(); //Glide.with(context).load(images).into(shopImg); shopImg.setImageURI(images); shopTitle.setText(childBeen.get(i).get(i1).getTitle()); shopPrice.setText(childBeen.get(i).get(i1).getPrice()+""); adv.setNumber(childBeen.get(i).get(i1).getNum()); //final Main2Activity main= (Main2Activity) context; //Control the visible and hidden if(childBeen.get(i).get(i1).isBtn()){ shop_delete.setVisibility(View.VISIBLE); }else{ shop_delete.setVisability(View.INVISIBLE); } //Delete button listening shop_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onDleGoods.onDelGoods(i,i1,childBeen.get(i).get(i1).getPid()+""); } }); //AddDelClickListener(new AddDeleteView.OnAddDelClickListener() { @Override public void onAddClick(View v) { int number = adv.getNumber(); number++; adv.setNumber(number); childBeen.get(i).get(i1).setNum(number); main.changesum(childBeen); } @Override public void onDelClick(View v) { int number = adv.getNumber(); if(number==1){ Toast.makeText(context,"The minimum number of users is 1",Toast.LENGTH_SHORT).show(); } number--; adv.setNumber(number); childBeen.get(i).get(i1).setNum(number); main.changesum(childBeen); } }); //Checkbox of secondary group listen childCb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean flag=false; boolean cchecked = childCb.isChecked(); childBeen.get(i).get(i1).setChildCb(cchecked); //Toast.makeText(context,"child button"+cchecked+""+i1, Toast.LENGTH_SHORT).show(); // Main2Activity main= (Main2Activity) context; for (List<ChildBean> i1:childBeen){ for(int r=0;r<i1.size();r++) { boolean childCb1 = i1.get(r).isChildCb(); if(!childCb1){ main.allCheckbox.setChecked(false); groupBeen.get(i).setGropuCb(false); flag=true; break; }else{ main.allCheckbox.setChecked(true); groupBeen.get(i).setGropuCb(true); } } if(flag){ break; } } int size = childBeen.get(i).size(); for(int x=0;x<size;x++) { boolean childCb1 = childBeen.get(i).get(x).isChildCb(); if(!childCb1){ groupBeen.get(i).setGropuCb(false); break; }else{ groupBeen.get(i).setGropuCb(true); } } notifyDataSetChanged(); main.changesum(childBeen); } }); return v; } @Override public boolean isChildSelectable(int i, int i1) { return false; }} 7.购物车页面逻辑Main2Activity
package com.bwei.gepeng.view; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.CheckBox; import android.widget.ExpandableListView; import android.widget.TextView; import com.bwei.gepeng.R; import com.bwei.gepeng.adapter.ExpandableAdapter; import com.bwei.gepeng.entity.CartBean; import com.bwei.gepeng.entity.ChildBean; import com.bwei.gepeng.entity.GroupBean; import com.bwei.gepeng.presenter.NewsPresenter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; importation java.util.map; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class Main2Activity extends AppCompatActivity implements IView { @BindView(R.id.exListView) ExpandableListView exListView; @BindView(R.id.all_chekbox) public CheckBox allCheckbox; @BindView(R.id.total_price) TextView totalPrice; @BindView(R.id.total_number) TextView totalnumber; @BindView(R.id.tv_go_to_pay) TextView tvGoToPay; @BindView(R.id.tv_go_to_del) TextView tvGoToDel; private ExpandableAdapter expandableAdapter; private boolean flagdel = true; private boolean flagdel = false; private NewsPresenter presenter; List<GroupBean> groupBeen = new ArrayList<>(); List<List<ChildBean>> childBeen = new ArrayList<>(); int i; int i1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); ButterKnife.bind(this); //Get the secondary list adapter expandableAdapter = new ExpandableAdapter(Main2Activity.this, groupBeen, childBeen); exListView.setAdapter(expandableAdapter); exListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) { return true; } }); presenter = new NewsPresenter(); presenter.attachView(this); //http://120.27.23.105/product/getCarts?uid=3802&source=android Map<String, String> map = new HashMap<>(); map.put("uid", "3802"); presenter.getData(map, "cart"); expandableAdapter.setOnDeleteGoods(new ExpandableAdapter.onDeleteGoods() { @Override public void onDelGoods(int i, int i1, String pid) { Main2Activity.this.i = i; Main2Activity.this.i1 = i1; Map<String, String> map = new HashMap<>(); map.put("uid", "3802"); map.put("pid", pid); presenter.getData(map, "del"); } }); } @Override public void OnSuccess(Object o, String tag) { if (tag.equals("cart")) { if (o != null) { List<CartBean> data = (List<CartBean>) o; for (CartBean i : data) { GroupBean groupBean = new GroupBean(i.getSellerName(), false); this.groupBeen.add(groupBean); List<CartBean.ListBean> list = i.getList(); List<ChildBean> ls = new ArrayList<>(); for (CartBean.ListBean w : list) { String[] split = w.getImages().split("//|"); ChildBean childBean = new ChildBean(w.getTitle(), split[0], w.getPrice(), 1, false, false, w.getPid()); ls.add(childBean); } this.childBeen.add(ls); } for (int i = 0; i < expandableAdapter.getGroupCount(); i++) { exListView.expandGroup(i); } } } else if (tag.equals("del")) { if (o != null) { String msg = (String) o; if (this.i != -1 && this.i1 != -1) { int size = childBeen.get(i).size(); if (size == 1) { childBeen.remove(i); groupBeen.remove(i); } else { childBeen.get(i).remove(i1); } changesum(childBeen); this.i = -1; this.i1 = -1; if(flagdel){ delGoods(); } } } } } } expandableAdapter.notifyDataSetChanged(); } @Override public void OnFailed(Exception e, String tag) { } @OnClick({R.id.back, R.id.edit, R.id.all_chekbox,R.id.tv_go_to_del}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.back: finish(); casser; case R.id.edit: if(flagedit){ tvGoToPay.setVisability(View.GONE); tvGoToDel.setVisability(View.VISIBLE); }else{ tvGoToPay.setVisability(View.VISIBLE); tvGoToDel.setVisability(View.GONE); } for (List<ChildBean> i1 : childBeen) { for (int r = 0; r < i1.size(); r++) { i1.get(r).setBtn(flagedit); } } flagedit = !flagedit; expandableAdapter.notifyDataSetChanged(); casser; case R.id.all_chekbox: boolean checked = allCheckbox.isChecked(); //Change the first-level item check box for (GroupBean i : groupBeen) { i.setGropuCb(checked); } //Change the second-level item check box for (List<ChildBean> i1 : childBeen) { for (int r = 0; r < i1.size(); r++) { i1.get(r).setChildCb(checked); } } expandableAdapter.notifyDataSetChanged(); changesum(childBeen); casser; case R.id.tv_go_to_del: if(childBeen.size()!=0){ for (List<ChildBean> i1 : childBeen) { for (int r = 0; r < i1.size(); r++) { boolean childCb1 = i1.get(r).isChildCb(); if (childCb1) { flagdel=true; delGoods(); if(allCheckbox.isChecked()){ allCheckbox.setChecked(false); } casser; } } if(flagdel){ break; } } } //Toast.makeText(Main2Activity.this,flagdel+"",Toast.LENGTH_SHORT).show(); casser; } } //Recursively delete private void delGoods(){ Boolean flag=false; for(int p=0;p<childBeen.size();p++) { for (int r = 0; r < childBeen.get(p).size(); r++) { boolean childCb1 = childBeen.get(p).get(r).isChildCb(); if(p==childBeen.size()-1&&r==childBeen.get(p).size()-1){ flagdel=false; } if (childCb1) { int pid = childBeen.get(p).get(r).getPid(); this.i = p; this.i1 = r; Map<String, String> map = new HashMap<>(); map.put("uid", "3802"); map.put("pid", pid+""); presenter.getData(map, "del"); flag=!flag; casser; } } if(flag){ break; } } } //Total price of calculation and quantity public void changesum(List<List<ChildBean>> childBeen) { int count = 0; double sum = 0; for (List<ChildBean> i1 : childBeen) { for (int r = 0; r < i1.size(); r++) { boolean childCb1 = i1.get(r).isChildCb(); if (childCb1) { double price = i1.get(r).getPrice(); int num = i1.get(r).getNum(); sum += price * num; count++; } } } totalPrice.setText("¥" + sum); totalnumber.setText("Total products:" + count + "piece"); }}6.附
shape图edit
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFFFFF" /> <!--<corners android:radius="3dip"/>--> <stroke android:width="1dip" android:color="#BDC7D8" /> </shape>
Application 初始化Fresco
import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; public class App extends Application{ @Override public void onCreate() { super.onCreate(); Fresco.initialize(this); }}The above is all the content of this article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.