Este artículo comparte el código específico del carrito de compras de implementación de modernización de Rxjava para la referencia de todos. El contenido específico es el siguiente
Imagen de reproducción:
1. Dependencia
AnotationProcessor 'Com.Jakewharton: Butterknife-Compiler: 8.8.1' Compilar 'com.Jakewharton: Butterknife: 8.8.1' Compilar 'com.android.support:recyclerview-v7:26.0.0-alpha1' Compile 'Com.SquareUp.rréfit2: retrofit: 2.3.0' 'com.squareup.ruprofit2: Converter-gson: 2.3.0' compilar 'com.facebook.fresco: fresco: 0.12.0' compilar 'com.facebook.fresco: support de base animada: 0.12.0' compilarse ' 'com.facebook.fresco: animated-webp: 0.12.0' compilar 'com.facebook.fresco: webpsupport: 0.12.0' compilar 'io.reactivex.rxjava2: rxJava: 2.1.7' compilado 'com.squareup.ruprofit2: adapter-rxjava2: 2.3.0' compil 'io.reactivex.rxjava2: rxandroid: 2.0.1' compilar 'com.squareup.okhttp3: okhttp: 3.9.0' compilar 'com.google.code.gson: gson: 2.8.1'
2. Diseño
1. Diseño del diseño del adición_add_delete
<? xml versión = "1.0" encoding = "utf-8"?> <linealLayout xmlns: android = "http://schemas.android.com/apk/res/Android" android: loinout_width = "Match_parent" android: Layout_height = "Match_Parent" Android: ientation = "Horizontal" y "1". <TextView Android: id = "@+id/txt_delete" android: Layout_width = "30DP" Android: Layout_height = "30DP" Android: Text = "Deduction" Android: Gravity = "Center" Android: Background = "#8B948b"/> <EditText android: Id = "@+id/et_number" Android: Layout_marGintOp = "2DP" Android: Layout_width = "50DP" Android: LELOOUT_HEight = "30DP" Android: Background = "@Drawable/Edit" Android: Layout_weight = "0.00" Android: Gravity = "Center" Android: Text = "1"/> <TextViek Android: Layout_width = "30DP" Android: Layout_height = "30DP" Android: Text = "Plus" Android: Gravity = "Center" Android: Background = "#8B948B"/> </LinearLayout>
2. Detalles del producto Diseño Actividad_main
<? xml versión = "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: layt ". Android: Layout_height = "Match_Parent"> <LinearLayout Android: Layout_width = "Match_Parent" Android: Layout_height = "Match_Parent" Android: Orientation = "Vertical"> <com.facebook.drawee.view.simpledraweeView android: id = "@+id/myimage_view" Android: Layout_width = "Match_Parent" Android: Layout_height = "450DP" Fresco: PlaceHolderImage = "@mipmap/ic_launcher"/> <textView android: id = "@+id/books_title" Android: Layout_width = "wrap_content" android: layo_height = "wrap_content" Android: Layout_margin = "10dp" android: text = "aahhh its es tuyo" Android: textSize = "20dp" /> <textView android: id = "@+id /beaTs_price" android: lozo_width = "wrap_content" android: lugar_height = "wrap_content" android: sayout_margin 10dp "10dp" 10dp "10dp" android: text = "¥ 18132" Android: textColor = "#dc5f2e" android: textSize = "18DP" /> <TextView android: LEING_WIDTH = "WRAP_CONTENT" Android: Layout_height = "Wrap_Content" Android: LayOut_Margin = "10DP" yid: Text = "I’s A'h A'h A'h A'h A'h" "" ". Android: textSize = "16DP"/> </LinearLayout> <LinearLayout Android: Layout_AlignParentBottom = "True" android: Layout_width = "Match_Parent" Android: Layout_Height = "50DP" Android: Orientación = "Horizontal"> <Botón Android: ID = "@+ID/BTN_ADDCART" Android: Layout_weight = "1" Android: Layout_width = "0DP" Android: Layout_Height = "Match_Parent" Android: Background = "#FFC207" Android: Text = "Agregar a Cart"/> <Button: id = "@+id/btn_shopping" Android: Layout_weight = "1" Android: Layout: Layout: Layout: Layout: "width Android: Layout_height = "Match_parent" Android: Background = "#FF6B06" Android: Text = "Buy Now"/> </ LineAleLayout> </RelativeLayout>
3. Actividad del diseño del carrito de compras_main2
<? xml versión = "1.0" encoding = "utf-8"?> <linealLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: loinout_width = "match_parent" Android: Layout_height = "Match_Parent" Android: ientation = "vertical"> <! <LinearLayout Android: id = "@+id/top_bar" Android: Layout_width = "Match_parent" Android: Layout_height = "48dp" Android: Background = "#F7F7F7" Android: Orientación = "VERTICAL"> <RelatiDliveAut Android: LayOut_Width = "Match_parent" android: Layout: Layoutwight " Android: Background = "@Android: Color/Transparent" Android: Orientation = "Vertical"> <ImageView Android: id = "@+id/back" Android: Layout_width = "48dp" Android: Layout_height = "48DP" Android: Layout_alignparentft = "True" android: Leout_gravity = "Center_Centerical" Android: Padding = "12DP" Android: src = "@drawable /back" /> <textView android: Layout_width = "Match_parent" Android: Layout_height = "Wrap_Content" Android: Gravity = "Center" Android: MinHeight = "48DP" Android: Text = "Compre Cart" Android: TextColor COLOR = "#"#1###"#"#"" Android: textSize = "16sp" /> <textView android: id = "@+id /edit" android: layout_width = "wrap_content" Android: Layout_height = "wrap_content" android: layout_alignParentright = "true" android: LEXOUT_MARGINGER = "40DP" Android: Gravity = "Center" Android: minheight = "48dp" android: text = "edit" android: textColor = "#1a1a1a" android: textSize = "14sp" android: visibilidad = "visible"/> </relativeLayout> </linealLayout> <expandableListView: id = "@+id/expListView" y sayout ". Android: Layout_height = "0DP" Android: Layout_weight = "1" Android: ChildIndicator = "@null" Android: GroupIndicator = "@null"> </expandableListView> <LinearLayout Android: LayOut_width = "Match_Parent" Android: LayOut_height = "50DP" android: Gravity = "" Everal " android: orientación = "horizontal"> <checkbox android: id = "@+id /all_chekbox" Android: Layout_marginleft = "20dp" android: LEING_WIDTH = "wrap_content" android: lay_height = "wrap_content" /> <extegiew android: lentout_width = "wrap_content" Android: Layout_height = "wrap_content" android: text = "Select All"/> <LinearLayout Android: id = "@+id/LL_info" android: Layout_width = "0dp" Android: Layout_height = "Wrap_Content" android: Layout_weight = "4"> <Linearlaut y Froid: Layout: Layout: Layout = " android:layout_height="wrap_content" android:orientation="vertical" 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 = "wrap_content" android: Layout_height = "wrap_content" android: layout_marginleft = "5dp" android: text = "total:" android: textsize = "18sp" android: textyle = "negring" /> <textView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="¥0.00" android:textColor="#f23232" android:textSize="16sp" android:textStyle="bold" /> </LinearLayout> <TextView android:id="@+id/total_number" Android: Layout_width = "Match_parent" Android: Layout_height = "wrap_content" android: text = "Total Products: 0 Pieces" Android: Gravity = "Right" Android: TextSize = "16Sp" Android: Textyle = "Bold"/> </ LinearLayout> <ExtView Android: id = "@+ID/TV_GO_TO_TODE_PAY" Android: Layout_width = "Match_Parent" Android: Layout_height = "Match_Parent" Android: Layout_weight = "3" Android: Background = "#FD7A05" Android: Clickable = "True" Android: Gravity = "Center" Android: Text = "Clear" Android: Textcolor = "#FAFAFA" /> <TextView "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"/> </LinealLayout> </lineAleLayout> </LinearLayout>
4. Lista secundaria Diseño de nivel de grupo ex_group_item
<? xml versión = "1.0" encoding = "utf-8"?> <linealLayout xmlns: android = "http://schemas.android.com/apk/res/android" Android: Layout_width = "Match_parent" Android: Layout_Height = "Match_Parent" Android: Incenture = "#cfc3c3" android: orientación = "horizontal"> <checkbox android: id = "@+id/group_checkbox" Android: Layout_marginleft = "20DP" android: LEING_WIDTH = "WRAP_CONTENT" Android: LayOut_height = "wrap_content" Android: enfocable = "false"/> <xetview yid: id = "@t step Android: Layout_marginleft = "20DP" Android: Layout_width = "wrap_content" Android: Layout_height = "wrap_content" android: textsize = "16dp" /> < /linealLayout>
5. Lista secundaria Sub-Layout ex_child_item
<? xml versión = "1.0" encoding = "utf-8"?> <linealLayout 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: orientación = "horizontal"> <Checkbox: id = "@+id/child_checkbox" y eleDoid: la orientación Android: Layout_marginleft = "20DP" Android: Layout_MarginBottom = "50DP" Android: Layout_Width = "Wrap_Content" Android: Layout_Height = "wrap_content" /> <relativeLayout android: layout_marginleft = "20dp" android: Layout_width = "" " 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" android: layout_alignparent = "verdadero" verdadero " Android: Layout_marginleft = "17DP" Android: LEING_MARGINSTART = "17DP" Android: text = "TextView" Android: Layout_alignParentTop = "True" /> <!-<ImageView Android: id = "@+id /shop_img" android: LayOut_width = "90dp" y leid: fielroid: fikeut: "" 900DP ". Android: Layout_MarGintOp = "30DP" App: srccompat = "@mipmap/ic_launcher" android: lazout_below = "@+id/shop_name" android: layout_alignparentleft = "true" android: Layout_alignParentStart = "True"/>-> <ComaFace.Viewe.View.View.View.View.SIMPLEDREMPLEDREA Android: id = "@+id/shop_img" Android: Layout_width = "90dp" Android: Layout_height = "90DP" Android: LEING_MARGINTOP = "30DP" Fresco: PlaceLoPherMage = "@mipmap/ic_launcher" android: layout_below = "@+id/shop_name" Android: Layout_alignParentLeft = "True" Android: Layout_AlignParentStart = "True"/> <TextView Android: id = "@+id/shop_price" android: Layout_width = "wrap_content" android: layout_height = "wrap_content" android: lentout_aligntop = "@+id/shop/shop Android: Layout_centerHorizontal = "True" Android: LEING_MARGINTOP = "10DP" Android: text = "¥ 20" Android: TextColor = "#F23232"/> <com.bwei.gepeng.myview.addddelelEview Android: id = "@+id/ad/ad/ad/adv" Android: sayout_width "160dp" 160dp "160dp" 160 Android: Layout_height = "30DP" Android: Layout_below = "@+id/shop_price" Android: LEXOUT_MARGINTOP = "30DP" Android: Layout_MarGinleft = "140DP" APP: Left_Text = "-" App: Right_Text = "+" App: Middle_Text = "1" Android: Focusable = " </com.bwei.gepeng.myview.adddeleteview> <botón android: id = "@+id/shop_delete" android: lazout_width = "wrap_content" android: locout_height = "wrap_content" Android: Layout_alignParentend = "True" android: Layoutharentrackin = "WRAP_CONTENT" True "verdadero" verdadero "verdadero" Android: Layout_centerverCical = "True" Android: Visibility = "Invisible" Android: Text = "Delete"/> </RelativeLayout> </LinealLayout>
3. Clase de entidad
1. MessageBean
paquete com.bwei.gepeng.entity; clase pública MessageBean <T> {Código de cadena privada; datos de T privado; msg de cadena privada; Vendedor privado Vendedor; public String getCode () {código de retorno; } public void setCode (código de cadena) {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 () {Vendedor de retorno; } public void setSeller (SellerBean Seller) {this.seller = Seller; } public static class SellerBean {/** * Descripción: Soy un comerciante 19 * icono: http://120.27.23.105/images/icon.png * Nombre: comerciante 19 * productnums: 999 * Puntuación: 5.0 * SellerID: 19 */Descripción de cadena privada; icono de cadena privada; nombre de cadena privada; Private int productnums; puntaje doble privado; Private int Sellerid; public String getDescription () {return Descripción; } public void setDescription (String Descripción) {this.description = Descripción; } public String getiCon () {return icon; } public void seticon (icon de cadena) {this.icon = icon; } public String getName () {nombre de retorno; } public void setName (nombre de cadena) {this.name = name; } public int getProductnums () {return productNums; } public void setProductnums (int productnums) {this.productnums = productnums; } public Double GetScore () {puntaje de retorno; } public void setScore (doble puntaje) {this.score = stork; } public int getSellerID () {return SellerID; } public void setSellerID (int sellerid) {this.sellerID = sellerId; }}}2.goodsshowbean
paquete com.bwei.gepeng.entity; Public Class GoodsShowBean {Privado de doble ganga privado; Cadena privada CreateToTime; DetailUrl de cadena privada; Imágenes de cadena privada; Private int itemType; privado int pid; precio doble privado; privado int pscid; Private int Salesenum; Private int Sellerid; subtítulo de cadena privada; título de cadena privada; public Double GetBargainPrice () {return BargainPrice; } public void setBarGainPrice (doble compuesto de negociación) {this.BarGainPrice = BargainPrice; } public String getCreateTime () {return CreateTime; } public void setCreateTime (String CreateTime) {this.CreateTime = CreateTime; } public String getDetailUrl () {return DetailUrl; } public void setDetailUrl (cadena detallurl) {this.detailUrl = DetellUrl; } public String getImages () {return imágenes; } public void setImages (imágenes de cadena) {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 () {Return Price; } public void setPrice (doble precio) {this.price = precio; } public int getPscid () {return pscid; } public void setPscid (int pscid) {this.pscid = pscid; } public int getSalenum () {return salesEnum; } public void setSalenum (int salsenum) {this.salenum = salesenum; } public int getSellerID () {return SellerID; } public void setSellerID (int sellerid) {this.sellerID = sellerId; } public String getSubhead () {return subhead; } public void setSubhead (String subhead) {this.subhead = subhead; } public String gettitle () {Título de retorno; } public void settitle (título de cadena) {this.title = title; } @Override public String toString() { return "GoodsShowBean{" + "bargainPrice=" + bargainPrice + ", createtime='" + createtime + '/'' + ", detailUrl='" + detailUrl + '/'' + ", images='" + images + '/'' + ", itemtype=" + itemtype + ", pid=" + pid + ", precio = " + precio +", pscid = " + pscid +", saleseNum = " + saledenum +", sellerId = " + sellerId +", subhead = '" + subhead +'/'' +", title = '" + title +'/'' + '}'; }}3. Cartbean
paquete com.bwei.gepeng.entity; import java.util.list; Cartbean de clase pública {String private String SellerName; Vendedor de cadenas privadas; Lista de lista privada <Listbean>; public String getSellerName () {return SellerName; } public void setSellerName (String SellerName) {this.sellername = sellerName; } public String getSellerID () {return SellerID; } public void setSellerId (String SellerID) {this.sellerID = SellerID; } Lista pública <LiCBean> getList () {return List; } public void setList (list <IndBean> list) {this.list = list; } public static class ListBean {Private Double BargainPrice; Cadena privada CreateToTime; DetailUrl de cadena privada; Imágenes de cadena privada; privado int num; privado int pid; precio doble privado; privado int pscid; private int seleccionado; Private int Sellerid; subtítulo de cadena privada; título de cadena privada; public Double GetBargainPrice () {return BargainPrice; } public void setBarGainPrice (doble compuesto de negociación) {this.BarGainPrice = BargainPrice; } public String getCreateTime () {return CreateTime; } public void setCreateTime (String CreateTime) {this.CreateTime = CreateTime; } public String getDetailUrl () {return DetailUrl; } public void setDetailUrl (cadena detallurl) {this.detailUrl = DetellUrl; } public String getImages () {return imágenes; } public void setImages (imágenes de cadena) {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 () {Return Price; } public void setPrice (doble precio) {this.price = precio; } public int getPscid () {return pscid; } public void setPscid (int pscid) {this.pscid = pscid; } public int getSelected () {return seleccionado; } public void setSelected (int seleccionado) {this.selected = seleccionado; } public int getSelerID () {return SellerID; } public void setSellerID (int sellerid) {this.sellerID = sellerId; } public String getSubhead () {return subhead; } public void setSubhead (String subhead) {this.subhead = subhead; } public String gettitle () {Título de retorno; } public void settitle (título de cadena) {this.title = title; }} @Override public String toString () {return "CartBean {" + "SellerName = '" + SellerName +'/'' + ", SellerId = '" + SellerId +'/'' + ", list =" + List + '}'; }}4. Groupbean
paquete com.bwei.gepeng.entity; Public Class GroupBean {String private String SellerName; Groupucb privado booleano; Public Groupbean (String SellerName, Boolean Groupucb) {this.sellername = SellerName; this.gropUCB = Groupucb; } public String getSellername () {return SellerName; } public void setSellerName (String SellerName) {this.sellername = sellerName; } public boolean isgropucB () {return groupucb; } public void setGropucB (boolean groupucb) {this.gropUCB = groupucb; } @Override public String toString () {return "groupbean {" + "sellerName = '" + sellerName +'/'' + ", groupucb =" + groupucb + '}'; }}5.Childbean
paquete com.bwei.gepeng.entity; Public Class Childbean {Título de cadena privada; Imágenes de cadena privada; precio doble privado; privado int num; Boolean ChildCB privado; booleano privado btn; privado int pid; Public Childbean (título de cadena, imágenes de cadena, doble precio, int num, boolean childcb, boolean btn, int pid) {this.title = title; this.Images = Images; this.price = precio; 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 () {Título de retorno; } public void settitle (título de cadena) {this.title = title; } public String getImages () {return imágenes; } public void setImages (imágenes de cadena) {this.Images = Images; } public Double GetPrice () {Return Price; } public void setPrice (doble precio) {this.price = precio; } 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 +'/'' + ", precio =" + precio + ", num =" + num + ", childcb =" + childCb + ", btn =" + btn + + ", pid =" + pid + '}; }}4. Interfaz
1.Apiservicio
paquete com.bwei.gepeng.http; import com.bwei.gepeng.entity.cartbean; import com.bwei.gepeng.entity.goodsshowbean; import com.bwei.gepeng.entity.messagebean; import java.util.list; import java.util.map; import io.reactivex.flowable; importación importar2.http.get; importación importar2.http.querymap; APIService de interfaz pública {// Detalles del producto de consulta 75 //http://120.27.23.105/product/getProductDetail?pid=75&source=Android @get ("Product/GetProductDetail") flujo de fluible <MessageBean <etsshowBean>> getNeWs (@QueryMap MAP <string, string> map ") Flowable <MessageBean <etsshowBean>> getNews (@QueryMap MAP <string, string> map") Flowable <MessageBean <etsshowBean>> GetNeWs (@QueryMap MAP <String, String, String> Map) // consulta compras carro // http: //120.27.23.105/product/getcarts? Uid = 3802 & source = android @get ("producto/getcarts") flujo <messageBean <list <artbean>>> getCart (@QueryMap Map <String, string> map); // Eliminar el carrito de compras // http: //120.27.23.105/product/getCarts? Uid = 3802 & source = android @get ("producto/deletecart") fluible <messageBean <list <artbean>>> getDel (@QueryMap Map <String, String> map); // Agregar carrito de compras // http: //120.27.23.105/product/addcart? Uid = 3802 & pid = 75 & source = android @get ("producto/addCart") flujoy <messageBean <list <CartBean>>> getAdd (@Querymap map <string> map); } 2.IView [java] ver la interfaz de copypublic sencillo iview {void onSuccess (objeto o, etiqueta de cadena); nulo onfailed (excepción e, etiqueta de cadena); } 3.ipresenter [java] ver simple copyimport java.util.map; interfaz pública iPresenter {void getData (map <string, string> map, string etiqueta); } 4.Imodel [java] Ver CopyImport simple java.util.map; interfaz pública imodel {void getData (map <string, string> map, string etiqueta); }5. Código
1. Vista personalizada AddDdelteview
paquete com.bwei.gepeng.myview; importardroid.content.context; importar android.content.res.typedarray; importardroid.graphics.color; importardroid.util.attributeset; importar android.view.view; importar android.widget.edittext; importar Android.Widget.LinearLayout; importardroid.widget.textView; import com.bwei.gepeng.r; Public Class AddDelteview extiende LinearLayout {Private OnaddelClickListener Listener; editText privado etnumber; // Proporcione una interfaz de devolución de llamada de clic para la interfaz pública de uso público OnAddDelClickListener {void onAddClick (Ver v); void ondelclick (ver v); } public void setonaddelClickListener (OnaddelClickListener oyer) {if (oyente! = null) {this.listener = oyente; }} public adddelelEview (contexto context) {this (context, null); } public addDelteview (contexto de contexto, atributeset attrs) {this (context, attrs, 0); } public addDelteview (contexto de contexto, atributeset attrs, int defstyleattr) {super (context, attrs, defstyleattr); initView (context, attrs, defstyleattr); } private void initView (contexto context, atributeset attrs, int defstyleattr) {ver.inflate (context, r.layout.layout_add_delete, this); // Obtener el control TextView txtDelete = findViewById (r.id.txt_delete); TextView txtAdd = findViewById (r.id.txt_add); etnumber = findViewById (r.id.et_number); TypedArray typedArray = context.obtainStyledAttributes (attrs, r.stylable.adddeletEviewStyle); String LeftText = typedArray.getString (r.stylable.adddeletEviewStyle_left_text); String RightText = typedArray.getString (r.stylable.adddeletEviewStyle_right_text); Cadena middletext = typedArray.getString (r.stylable.adddeletEviewStyle_middle_text); int color = typedArray.getColor (r.stylable.adddeletEviewStyle_left_text_color, color.red); txtDelete.setText (LeftText); txtadd.settext (righttext); etnumber.settext (middletext); txtdelete.setTextColor (color); // reciclar typedArray.Recycle (); txtDelete.setOnClickListener (new OnClickListener () {@Override public void onClick (Ver View) {LOYER.ONDELCLICK (Ver);}}); txtadd.setOnClickListener (new OnClickListener () {@Override public void onClick (ver vista) {oyente.onaddclick (ver);}}); } // Proporcionar un método externo para modificar los números public void setNumber (int number) {if (número> 0) {etnumber.settext (número+""); }} // Proporcione un método externo para obtener el número actual público int getNumber () {String String = etnumber.gettext (). ToString (); int i = Integer.ParseInt (String); regresar i; }} 2. Medicetización
paquete com.bwei.gepeng.http; import java.io.ioException; import okhttp3.httpurl; import okhttp3.interceptor; import okhttp3.okhttpClient; import okhttp3.request; importar okhttp3.Response; importar Remieve2.Recrofit; importación importar2.Adapter.rxjava2.rxjava2CalladapterFactory; importación de importación2.converter.gson.gsonconverterFactory; MetRoFitUtils de clase pública {instancia de retrofitutils volátiles estáticos privados; modernización de modernización final privada; private retrofitUtils () {okhttpClient Client = new OkhttpClient.Builder (). AddInterceptor (new Logger ()). Build (); retrofit = new Retrofit.Builder (). Cliente (Cliente) .addCalladapterFactory (rxJava2CalladapterFactory.Create ()) .addConverterFactory (gsonConverterFactory.create ()) .baseurl ("http://120.27.23.105/"). } public static retrofitUtils getInStance () {if (instance == null) {sincronizado (retrofitUtils.class) {if (instance == null) {instancia = nuevo retrofitUtils (); }}} instancia de retorno; } public apiservice getApiservice () {apiservice apiservice = retrofit.create (apiservice.class); APIService de retorno; } La clase Logger implementa Interceptor {@Override Public Response Intercept (Chain Chain) lanza ioexception {request original = chain.request (); Httpurl url = original.url (). NewBuilder () .AddQueryParameter ("fuente", "Android") .Build (); // Agregar solicitud de solicitud de encabezado de solicitud = original.newBuilder () .URL (url) .Build (); return chain.proceed (solicitud); }}} 3. Capa de M
paquete com.bwei.gepeng.model; import com.bwei.gepeng.entity.cartbean; import com.bwei.gepeng.entity.goodsshowbean; import com.bwei.gepeng.entity.messagebean; import com.bwei.gepeng.http.rretrofitutils; import com.bwei.gepeng.presenter.newspresenter; import java.util.list; import java.util.map; import io.reactivex.flowable; El modelo de clase pública implementa imodel {presentador privado de periódicos; Modelo público (presentador de periódicos) {this.presenter = presentador; } @Override public void getData (map <string, string> map, string tag) {if (tag.equals ("cart")) {flukable <messageBean <list <artbean>>> flujo = retrofitUtils.getInstance (). GetApiservice (). GetCart (map); presentador.get2 (Flowable, tag); } else if (tag.equals ("bienes")) {fluable <messageBean <GoodsShowBean>> flujo = retrofitUtils.getInstance (). getApiservice (). getNews (map); presentador.get (flujoable, etiqueta); } else if (tag.equals ("del")) {Flowable <MessageBean <List <CartBean>>> Flowable = retrofitUtils.getInStance (). GetApiservice (). GetDel (MAP); presentador.get3 (Flowable, TAG); } else if (tag.equals ("add")) {fluable <messageBean <list <CartBean>>> flujo = retrofitUtils.getInstance (). getApiservice (). getAdd (map); presentador.get4 (flujoable, etiqueta); }}} 4.P Capa
paquete com.bwei.gepeng.presenter; import com.bwei.gepeng.entity.cartbean; import com.bwei.gepeng.entity.goodsshowbean; import com.bwei.gepeng.entity.messagebean; import com.bwei.gepeng.model.model; import com.bwei.gepeng.view.iview; import java.util.list; import java.util.map; import io.reactivex.flowable; import io.reactivex.android.schedulers.androidschedulers; import io.reactivex.schedulers.schedulers; import io.reactivex.subscrips.DisposableSubsCriber; Public Class NewsPresenter implementa IPresenter {privado iview iview; Private DisposableSubScriber <MessageBean <GoodsShowBean>> suscriptor; Private DisposableSubScriber <MessageBean <list <artbean>>> suscriptor2; Private DisposableSubScriber <MessageBean <list <artbean>>> suscriptor3; Private DisposableSubScriber <MessageBean <list <artbean>>> suscriptor4; public void settinView (iview iview) {this.iview = iview; } @Override public void getData (map <string, string> map, string etiqueta) {modelo modelo = nuevo modelo (esto); modelo.getData (mapa, etiqueta); } public void DETACHVIEW () {if (iview! = null) {iview = null; } if (suscribe! = null) {if (! Subscriber.isDisposse ()) {suscripter.dispose (); }} if (suscriber2! = null) {if (! Subscriber2.isDisposse ()) {suscriber2.dispos (); }} if (suscriber3! = null) {if (! Subscriber3.isDisposse ()) {suscriber3.dispose (); }} if (suscriber4! = null) {if (! Subscriber4.isDisposse ()) {suscriber4.dispose (); }}} // Consulta el carrito de compras public Void get (Flowable <MessageBean <GoodsShowBean>> Flowable, Final String Tag) {subscriber = fluible public void onNext (MessageBean <ShetsShowBean> listMessAgebean) {if (listMessAgebean! = public void onComplete () {}}); } // consulta detalles del producto75 public void get2 (fluible <messageBean <list <artBean>>> flujoable, etiqueta de cadena final) {subscriber2 = flukable.subscriteon (schedulers.io ()) .Observeon (androidSchedulers.Mainthread ()) .SubScribeWith (new ProSableSableScibribRibribRebean <s MessageBean <LITS /LITSHIRSHEAT ()). @Override Void onNext (MessageBean <List <CartBean>>> List) {if (list! = @Override public void onComplete () {}}); } // Eliminar el carrito de compras public void get3 (fluible <messageBean <list <artBean>>> flujoable, etiqueta de cadena final) {subscriber3 = flukable.subscribeon (schedulers.io ()) .ObServeOn (androidSchedulers.Mainthread ()) .SubScribewith (newPoSableSableSubsCriberScriber <SmessageBean <CartBean>>>> ) (@SsubRide> public void onNext (MessageBean <list <artbean>> list) {if (list! = null) {string code = list.getMsg (); } // Agregar carrito de compras public void get4 (flujoable <messageBean <list <artBean>>> flujo, etiqueta de cadena final) {subscriber4 = fluable.subscribeon (schedulers.io ()) .Observeon (androidSchedulers.Mainthread (). void onNext (MessageBean <list <artbean>>> list) {if (list! = null) {string code = list.getMsg (); }} 5. Página de detalles del producto MainActivity
paquete com.bwei.gepeng.view; importardroid.content.intent; importar android.os.bundle; importardroid.support.v7.app.appcompatactivity; importar android.view.view; importardroid.widget.textView; importardroid.widget.toast; import com.bwei.gepeng.r; import com.bwei.gepeng.entity.goodsshowbean; import com.bwei.gepeng.presenter.newspresenter; import com.facebook.drawee.view.simpledraweeview; import java.util.hashmap; import java.util.map; Importar Butterknife.BindView; Importar Butterknife. Butterknife; Importar Butterknife.enclick; Public Class MainActivity extiende AppCompatActivity implementos iview {@bindview (r.id.my_image_view) SimpledRaweeView myImageView; @BindView (r.id.goods_title) TextView GoodStitle; @BindView (r.id.goods_price) TextView GoodsPrice; presentador de periódicos privados; @Override protegido void onCreate (Bundle SaveDInStancestate) {super.oncreate (saveDInStancestate); setContentView (r.layout.activity_main); Butterknife.bind (esto); presentador = new NewsPresenter (); presentador.attachview (esto); //http://120.27.23.105/product/getProductDetail?pid=75&source=Android map <string, string> map = new Hashmap <> (); map.put ("pid", "75"); presentador.getData (mapa, "bienes"); } @Override public void onSuccess (objeto o, etiqueta de cadena) {if (tag.equals ("bienes")) {if (o! = Null) {GoodsShowBean data = (GoodsShowBean) o; //Log.e("gp "," onSuccess: " + data.ToString ()); myiMageView.setImageuri (data.getImages (). Split ("// |") [0]); GoodStitle.settext (data.gettitle ()); GoodsPrice.setText ("¥"+data.getPrice ()); }} else if (tag.equals ("add")) {if (o! = null) {string msg = (string) o; Toast.maketeext (mainActivity.THIS, MSG, toast.length_short) .show (); }}} @Override public void onFailed (excepción e, etiqueta de cadena) {} @OnClick ({r.id.btn_addcart, r.id.btn_shopping}) public void onviewClicked (ver) {switch (ver.getId ()) {case r.id.btn_addcarart: map <string> map = new Hashmap <); map.put ("uid", "3802"); map.put ("pid", "75"); presentador.getData (mapa, "agregar"); //Toast.maketeext(mainActivity.this."add con éxito ", toast.length_short) .show (); romper; Caso R.ID.BTN_SHOPPing: intento intento = nuevo intento (mainActivity.THIS, main2activity.class); startActivity (intención); romper; }}} 6. Adaptador de lista secundaria ExpandableAdapter
paquete com.bwei.gepeng.Adapter; importardroid.content.context; importar android.view.view; importardroid.view.viewgroup; importar android.widget.baseExpandableListApter; importardroid.widget.button; importar android.widget.eckbox; importardroid.widget.textView; importardroid.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; import 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(); romper; 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(); romper; 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); romper; 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); } romper; } } if(flagdel){ break; } } } //Toast.makeText(Main2Activity.this,flagdel+"",Toast.LENGTH_SHORT).show(); romper; } } //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; romper; } } 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); }}Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.