二级购物车+MVP

来源:互联网 发布:电脑群发短信软件 免费 编辑:程序博客网 时间:2024/06/13 23:24

这里写图片描述

适配器布局adapter_layout.xml里面gouwuche.bwei.com.mvpshop.view.PlusView注意这块要写成自己的

build.gradle

    apply plugin: 'com.android.application'    android {    compileSdkVersion 25    buildToolsVersion "26.0.2"    defaultConfig {        applicationId "gouwuche.bwei.com.mvpshop"        minSdkVersion 15        targetSdkVersion 25        versionCode 1        versionName "1.0"    }    buildTypes {        release {            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }    }    dependencies {        compile fileTree(dir: 'libs', include: ['*.jar'])        testCompile 'junit:junit:4.12'        compile 'com.android.support:appcompat-v7:25.+'        compile 'com.android.support:recyclerview-v7:25.3.1'        compile 'com.squareup.okhttp3:okhttp:3.9.0'        compile 'com.google.code.gson:gson:2.8.2'        compile 'com.jakewharton:butterknife:8.8.1'        compile 'com.jakewharton:butterknife-compiler:8.8.1'        compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'    }

清单列表

       <?xml version="1.0" encoding="utf-8"?>    <manifest xmlns:android="http://schemas.android.com/apk/res/android"        package="gouwuche.bwei.com.mvpshop">        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />        <uses-permission android:name="android.permission.INTERNET" />        <application            android:allowBackup="true"            android:icon="@mipmap/ic_launcher"            android:label="@string/app_name"            android:supportsRtl="true"            android:theme="@style/AppTheme">            <activity android:name=".activity.MainActivity">                <intent-filter>                    <action android:name="android.intent.action.MAIN" />                    <category android:name="android.intent.category.LAUNCHER" />                </intent-filter>            </activity>        </application>    </manifest>

activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"        android:orientation="vertical" android:layout_width="match_parent"        android:layout_height="match_parent">        <android.support.v7.widget.RecyclerView            android:id="@+id/third_recyclerview"            android:layout_width="match_parent"            android:layout_height="0dp"            android:layout_weight="1"            />        <LinearLayout            android:layout_weight="0"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal"            android:background="#FFFFFF"            android:gravity="center_vertical"            android:id="@+id/third_pay_linear"            >            <CheckBox                android:id="@+id/third_allselect"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_marginLeft="@dimen/margin_10dp"                android:drawableLeft="@drawable/shopcart_selected"                android:text="全选"                android:drawablePadding="@dimen/padding_5dp"                />            <LinearLayout                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_weight="1"                android:orientation="vertical"                >                <TextView                    android:id="@+id/third_totalprice"                    android:layout_width="200dp"                    android:layout_height="wrap_content"                    android:paddingLeft="@dimen/padding_10dp"                    android:paddingTop="@dimen/padding_10dp"                    android:text="总价:"                    android:textColor="@color/cblack"                    android:textSize="@dimen/common_font_size_16"                    />                <TextView                    android:textColor="@color/cblack"                    android:id="@+id/third_totalnum"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:paddingLeft="@dimen/padding_10dp"                    android:text="共0件商品"                    android:textSize="@dimen/common_font_size_14"                    android:paddingBottom="@dimen/padding_10dp"                    />            </LinearLayout>            <TextView                android:id="@+id/third_submit"                android:layout_width="wrap_content"                    android:layout_height="wrap_content"                android:background="@drawable/login_btn"                android:text="去结算"                android:paddingLeft="@dimen/margin_30dp"                android:paddingRight="@dimen/margin_30dp"                android:paddingTop="@dimen/padding_10dp"                android:paddingBottom="@dimen/padding_10dp"                android:textColor="#000000"                android:layout_marginRight="@dimen/margin_10dp"                />        </LinearLayout>    </LinearLayout>

adapter_layout.xml

      <?xml version="1.0" encoding="utf-8"?>    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"        android:orientation="vertical" android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="@color/cwhite">        <LinearLayout            android:id="@+id/ll_shopcart_header"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="vertical"            >            <View                android:layout_width="match_parent"                android:layout_height="@dimen/margin_10dp"                android:background="@color/background_color"                android:id="@+id/view"/>            <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:gravity="center_vertical"                >                <!-- 商店checkbox -->                <CheckBox                    android:id="@+id/shop_checkbox"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:src="@drawable/shopcart_selected"                    android:paddingLeft="@dimen/margin_15dp"                    android:paddingRight="@dimen/margin_15dp"                    android:paddingTop="@dimen/margin_10dp"                    android:paddingBottom="@dimen/margin_10dp"                    />                <!-- 商店明晨 -->                <TextView                    android:textColor="@color/cblack"                    android:id="@+id/tv_item_shopcart_shopname"                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:drawableLeft="@drawable/shopcart_shop"                    android:text="宝儿家服装"                    android:padding="@dimen/padding_10dp"                    android:drawablePadding="@dimen/padding_5dp"                    />            </LinearLayout>        </LinearLayout>        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:gravity="center_vertical"            >            <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:orientation="vertical"                >                <View                    android:layout_width="match_parent"                    android:layout_height="@dimen/margin_1dp"                    android:background="@color/background_color"                    />                <LinearLayout                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:orientation="horizontal"                    android:gravity="center_vertical"                    >                    <!-- 商品 checkbox -->                    <CheckBox                        android:id="@+id/item_checkbox"                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:src="@drawable/shopcart_selected"                        android:padding="@dimen/margin_15dp"                        />                    <!-- 商品图片 -->                    <ImageView                        android:id="@+id/item_pic"                        android:layout_width="60dp"                        android:layout_height="60dp"                        android:layout_margin="@dimen/margin_10dp"                        />                    <LinearLayout                        android:layout_width="0dp"                        android:layout_height="wrap_content"                        android:layout_weight="1"                        android:orientation="vertical"                        >                        <TextView                            android:id="@+id/item_price"                            android:layout_width="wrap_content"                            android:layout_height="wrap_content"                            android:text="¥185"                            android:textColor="@color/main_red_text"                            android:textSize="@dimen/common_font_size_14"                            />                        <LinearLayout                            android:layout_width="wrap_content"                            android:layout_height="wrap_content"                            android:layout_marginTop="@dimen/margin_5dp"                            android:layout_marginBottom="@dimen/margin_5dp"                            >                            <TextView                                android:textColor="@color/cblack"                                android:id="@+id/item_name"                                android:layout_width="wrap_content"                                android:layout_height="wrap_content"                                android:text="颜色:黑色"                                android:textSize="@dimen/common_font_size_12"                                />                            <TextView                                android:textColor="@color/cblack"                                android:id="@+id/tv_item_shopcart_cloth_size"                                android:layout_width="wrap_content"                                android:layout_height="wrap_content"                                android:textSize="@dimen/common_font_size_12"                                android:layout_marginLeft="@dimen/margin_10dp"                                />                        </LinearLayout>                        <gouwuche.bwei.com.mvpshop.view.PlusView                            android:layout_width="100dp"                            android:layout_height="wrap_content"                            android:id="@+id/plus_view_id"/>                    </LinearLayout>                    <View                        android:layout_width="@dimen/margin_1dp"                        android:layout_height="match_parent"                        android:layout_marginTop="@dimen/padding_10dp"                        android:layout_marginBottom="@dimen/padding_10dp"                        android:background="@color/splitline_color"                        />                    <ImageView                        android:id="@+id/item_del"                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:padding="@dimen/margin_20dp"                        android:src="@drawable/shopcart_delete"                        />                </LinearLayout>            </LinearLayout>        </LinearLayout>        <View            android:layout_width="match_parent"            android:layout_height="@dimen/margin_1dp"            android:background="@color/background_color"            />    </LinearLayout>

plus_layout.xml

    <?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">        <Button            android:layout_width="10dp"            android:layout_height="wrap_content"            android:id="@+id/revserse"            android:text="-"            android:background="#00FFFFFF"/>        <EditText            android:inputType="number"            android:text="1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/content"/>        <Button            android:background="#00FFFFFF"            android:text="+"            android:id="@+id/add"            android:layout_width="10dp"            android:layout_height="wrap_content"            />      </LinearLayout>

drawable文件里面 三个布局配置
ic_launcher_background.xml

        <?xml version="1.0" encoding="utf-8"?>        <vector xmlns:android="http://schemas.android.com/apk/res/android"            android:width="108dp"            android:height="108dp"            android:viewportHeight="108"            android:viewportWidth="108">            <path                android:fillColor="#26A69A"                android:pathData="M0,0h108v108h-108z" />            <path                android:fillColor="#00000000"                android:pathData="M9,0L9,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M19,0L19,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M29,0L29,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M39,0L39,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M49,0L49,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M59,0L59,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M69,0L69,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M79,0L79,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M89,0L89,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M99,0L99,108"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,9L108,9"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,19L108,19"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,29L108,29"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,39L108,39"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,49L108,49"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,59L108,59"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,69L108,69"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,79L108,79"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,89L108,89"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M0,99L108,99"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M19,29L89,29"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M19,39L89,39"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M19,49L89,49"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M19,59L89,59"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M19,69L89,69"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M19,79L89,79"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M29,19L29,89"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M39,19L39,89"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M49,19L49,89"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M59,19L59,89"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M69,19L69,89"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />            <path                android:fillColor="#00000000"                android:pathData="M79,19L79,89"                android:strokeColor="#33FFFFFF"                android:strokeWidth="0.8" />        </vector>

login_btn.xml

        <?xml version="1.0" encoding="utf-8"?>        <shape xmlns:android="http://schemas.android.com/apk/res/android">            <corners android:radius="@dimen/height_200dp"></corners>            <solid android:color="@color/pressed_icon_color"></solid>        </shape>

shopcart_add_btn.xml

        <?xml version="1.0" encoding="utf-8"?>        <shape xmlns:android="http://schemas.android.com/apk/res/android">            <corners android:radius="@dimen/height_200dp"></corners>            <stroke android:color="@color/background_color"       android:width="1dp"></stroke>        </shape>

colors.xml配置

    <?xml version="1.0" encoding="utf-8"?>    <resources>        <color name="colorPrimary">#3F51B5</color>        <color name="colorPrimaryDark">#303F9F</color>        <color name="colorAccent">#FF4081</color>        <color name="cwhite">#FFFFFF</color>        <color name="title_bg">#FDE23D</color>        <color name="tab_bg">#FFFFFF</color>        <color name="tab_normal_textcolor">#373737</color>        <color name="tab_selected_textcolor">#FDE23D</color>        <color name="coffer">#442509</color>        <color name="pressed_icon_color">#e53e42</color>        <color name="background_color">#f6f6f6</color>        <color name="main_red_text">#e53e42</color>        <dimen name="padding_20dp">20dp</dimen>        <color name="splitline_color">#dddddd</color>        <color name="cblack">#000000</color>    </resources>

dimens.xml配置

    <resources>        <!-- Default screen margins, per the Android Design guidelines. -->        <dimen name="margin_10dp">10dp</dimen>        <dimen name="padding_5dp">5dp</dimen>        <dimen name="padding_10dp">10dp</dimen>        <dimen name="common_font_size_16">16sp</dimen>        <dimen name="common_font_size_14">14sp</dimen>        <dimen name="height_200dp">200dp</dimen>        <dimen name="margin_30dp">30dp</dimen>        <dimen name="margin_15dp">15dp</dimen>        <dimen name="margin_1dp">1dp</dimen>        <dimen name="margin_5dp">5dp</dimen>        <dimen name="common_font_size_12">12sp</dimen>        <dimen name="padding_2dp">2dp</dimen>        <dimen name="margin_20dp">20dp</dimen>    </resources>

(M层)MainModel

    package gouwuche.bwei.com.mvpshop.model;    import gouwuche.bwei.com.mvpshop.bean.ShopBean;    import gouwuche.bwei.com.mvpshop.okhttp.AbstractUiCallBack;    import gouwuche.bwei.com.mvpshop.okhttp.OkhttpUtils;    /**     * Created by Adminjs on 2017/11/21.     */    public class MainModel {        public void getData(final MainModelCallBack callBack) {            OkhttpUtils.getInstance().asy(null, "http://120.27.23.105/product/getCarts?uid=100", new AbstractUiCallBack<ShopBean>() {                @Override                public void success(ShopBean bean) {                    callBack.success(bean);                }                @Override                public void failure(Exception e) {                     callBack.failure(e);                }            });        }    }

MainModelCallBack

    package gouwuche.bwei.com.mvpshop.model;    import gouwuche.bwei.com.mvpshop.bean.ShopBean;    /**     * Created by Adminjs on 2017/11/21.     */    public interface MainModelCallBack {       public void success(ShopBean bean);       public void failure(Exception e);    }

(V)MainViewListener

    package gouwuche.bwei.com.mvpshop.view;    import gouwuche.bwei.com.mvpshop.bean.ShopBean;    /**     * Created by Adminjs on 2017/11/21.     */    public interface MainViewListener {        public void success(ShopBean bean);        public void failure(Exception e);    }

(P)MainPresenter

    package gouwuche.bwei.com.mvpshop.presenter;    import gouwuche.bwei.com.mvpshop.bean.ShopBean;    import gouwuche.bwei.com.mvpshop.model.MainModel;    import gouwuche.bwei.com.mvpshop.model.MainModelCallBack;    import gouwuche.bwei.com.mvpshop.view.MainViewListener;    /**     * Created by Adminjs on 2017/11/21.     */    public class MainPresenter {        private MainViewListener listener;        private MainModel mainModel;        public MainPresenter(MainViewListener listener) {            this.listener = listener;            this.mainModel = new MainModel();        }        public void getData(){            mainModel.getData(new MainModelCallBack() {                @Override                public void success(ShopBean bean) {                    if (listener != null){                        listener.success(bean);                    }                }                @Override                public void failure(Exception e) {                     if (listener != null){                         listener.failure(e);                     }                }            });        }        public void detach(){            listener = null;        }    }

OkHttp

    package gouwuche.bwei.com.mvpshop.okhttp;    import java.io.File;    import java.util.Map;    import java.util.concurrent.TimeUnit;    import okhttp3.FormBody;    import okhttp3.MediaType;    import okhttp3.MultipartBody;    import okhttp3.OkHttpClient;    import okhttp3.Request;    import okhttp3.RequestBody;    /**     * Created by muhanxi on 17/11/10.     *     *     * Okhttp 单例 范型的封装     */    public class OkhttpUtils {        private static OkhttpUtils okhttpUtils = null ;        private OkhttpUtils(){        }            public static OkhttpUtils getInstance(){                if(okhttpUtils == null){                    okhttpUtils = new OkhttpUtils();                    client = new OkHttpClient.Builder()                            .readTimeout(20, TimeUnit.SECONDS)                            .writeTimeout(20,TimeUnit.SECONDS)                            .connectTimeout(20,TimeUnit.SECONDS)                            //添加拦截器                            .addInterceptor(new LoggingInterceptor())                            .build();                }                return okhttpUtils ;            }        private static OkHttpClient client ;        /**         * 发起异步请求         * @param params         * @param url         * @param callBack         */        public void asy(Map<String,String> params,String url,AbstractUiCallBack callBack){            Request request = null ;            if(params != null){                // post 请求                FormBody.Builder builder = new FormBody.Builder() ;                for(Map.Entry<String,String> entry : params.entrySet()){                    builder.add(entry.getKey(),entry.getValue());                }                FormBody body =  builder.build();                request = new Request.Builder()                        .url(url)                        .post(body)                        .build();            } else {                // get 请求                request = new Request.Builder()                        .url(url)                        .build();            }            client.newCall(request).enqueue(callBack);        }        private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");        public static void postFile(Map<String,String> map, String url, File file,AbstractUiCallBack callBack){            String [] array =  file.getAbsolutePath().split("\\/");            MultipartBody.Builder builder = new MultipartBody.Builder();            builder.setType(MultipartBody.FORM);            for(Map.Entry<String,String> entry : map.entrySet()){                builder.addFormDataPart(entry.getKey(),entry.getValue());            }            builder.addFormDataPart("imageFileName",array[array.length-1]);            if(file.exists() && file.length() > 0){                builder.addFormDataPart("image",array[array.length-1], RequestBody.create(MEDIA_TYPE_PNG,file));            }            MultipartBody body =  builder.build() ;            Request request = new Request.Builder()                    .url(url)                    .post(body)                    .build();            client.newCall(request).enqueue(callBack);        ]    }

AbstractUiCallBack

     package gouwuche.bwei.com.mvpshop.okhttp;    import android.os.Handler;    import android.os.Looper;    import com.google.gson.Gson;    import com.google.gson.JsonSyntaxException;    import java.io.IOException;    import java.lang.reflect.ParameterizedType;    import java.lang.reflect.Type;    import okhttp3.Call;    import okhttp3.Callback;    import okhttp3.Response;    /**     * Created by muhanxi on 17/11/10.     *     *  * Okhttp 单例 范型的封装     */    public  abstract  class AbstractUiCallBack<T> implements Callback {        /**         * 成功回调         * @param t         */        public abstract void success(T t);        /**         * 失败回调         * @param e         */        public abstract void failure(Exception e);        private Handler handler = null ;        private Class clazz ;        public AbstractUiCallBack(){            handler = new Handler(Looper.getMainLooper());            //  得到的是一个 AbstractUiCallBack<T> 的Type           Type type =  getClass().getGenericSuperclass() ;            // 得到的是T的实际Type           Type [] arr =  ((ParameterizedType)type).getActualTypeArguments() ;            clazz = (Class) arr[0] ;        }        @Override        public void onFailure(Call call, IOException e) {            failure(e);        }        @Override        public void onResponse(Call call, Response response) throws IOException {            try {                String result = response.body().string();                System.out.println("result = " + result);                Gson gson = new Gson();                final T t = (T) gson.fromJson(result,clazz);                handler.post(new Runnable() {                    @Override                    public void run() {                        success(t);                    }                });            } catch (IOException e) {                e.printStackTrace();                failure(e);            } catch (JsonSyntaxException e) {                e.printStackTrace();                failure(e);            }        }    }

(拦截器)LoggingInterceptor

       package gouwuche.bwei.com.mvpshop.okhttp;    import java.io.IOException;    import okhttp3.FormBody;    import okhttp3.Interceptor;    import okhttp3.Request;    import okhttp3.RequestBody;    import okhttp3.Response;    /**     * 可以实现 添加公共请求参数     */    public class LoggingInterceptor implements Interceptor {      @Override public Response intercept(Chain chain) throws IOException {        //首先取到Request        Request request = chain.request();        Response response = null;        Request requestProcess = null ;        if("GET".equals(request.method())){          String url =  request.url().toString() + "&source=android";          Request.Builder builder =  request.newBuilder() ;          builder.get().url(url);          requestProcess =  builder.build();          response = chain.proceed(requestProcess);        } else {          FormBody.Builder builder = new FormBody.Builder() ;          RequestBody requestBody =  request.body() ;          if(requestBody instanceof FormBody){            FormBody formBody = (FormBody)requestBody ;            for (int i=0;i<formBody.size();i++){              builder.add(formBody.encodedName(i),formBody.encodedValue(i));            }            builder.add("source","android");          }           requestProcess =  request.newBuilder().url(request.url().toString()).post(builder.build()).build() ;          response = chain.proceed(requestProcess);        }        return response;      }    }   

(加减购物车 自定义View)PlusView

        package gouwuche.bwei.com.mvpshop.view;    import android.content.Context;    import android.support.annotation.Nullable;    import android.text.Editable;    import android.text.TextWatcher;    import android.util.AttributeSet;    import android.view.LayoutInflater;    import android.view.View;    import android.widget.Button;    import android.widget.EditText;    import android.widget.LinearLayout;    import gouwuche.bwei.com.mvpshop.R;    /**     * Created by Adminjs on 2017/11/21.     */    /**     * 购物车加减号 自定义View     */    public class PlusView extends LinearLayout {        private EditText editText;        private Button revserse;        private Button add;        private int mCount = 1 ;        public PlusView(Context context) {            super(context);        }        public PlusView(Context context, @Nullable AttributeSet attrs) {            super(context, attrs);            View view =   LayoutInflater.from(context).inflate(R.layout.plus_layout,null,false);            revserse = (Button) view.findViewById(R.id.revserse);            add = (Button) view.findViewById(R.id.add);            editText = (EditText) view.findViewById(R.id.content);            revserse.setOnClickListener(new OnClickListener() {                @Override                public void onClick(View view) {                    //减号                    try {                        String content =  editText.getText().toString().trim() ;                        int count =  Integer.valueOf(content);                        if(count > 1){                            mCount = count-1;                            editText.setText(mCount+"");                            if(listener != null){                                listener.click(mCount);                            }                        }                    } catch (NumberFormatException e) {                        e.printStackTrace();                    }                }            });            add.setOnClickListener(new OnClickListener() {                @Override                public void onClick(View view) {                    //加号                    try {                        String content =  editText.getText().toString().trim() ;                        int count =  Integer.valueOf(content)+1;                        mCount = count;                        editText.setText(count+"");                        if(listener != null){                            listener.click(count);                        }                    } catch (NumberFormatException e) {                        e.printStackTrace();                    }                }            });            editText.addTextChangedListener(new TextWatcher() {                @Override                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {                }                @Override                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {                }                @Override                public void afterTextChanged(Editable editable) {                }            });            addView(view);        }        public PlusView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {            super(context, attrs, defStyleAttr);        }        public void setEditText(int num){            if(editText != null){                editText.setText(num+"");            }        }        public ClickListener listener;        public void setListener(ClickListener listener){            this.listener = listener;        }        /**         * 加减号 点击事件         */        public interface ClickListener {            public void click(int count);        }    }

适配器ShopAdapter

    package gouwuche.bwei.com.mvpshop.adapter;    import android.content.Context;    import android.support.v7.widget.RecyclerView;    import android.view.View;    import android.view.ViewGroup;    import android.widget.CheckBox;    import android.widget.ImageView;    import android.widget.LinearLayout;    import android.widget.TextView;    import com.nostra13.universalimageloader.core.ImageLoader;    import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;    import java.util.ArrayList;    import java.util.HashMap;    import java.util.List;    import java.util.Map;    import butterknife.BindView;    import butterknife.ButterKnife;    import gouwuche.bwei.com.mvpshop.R;    import gouwuche.bwei.com.mvpshop.bean.ShopBean;    import gouwuche.bwei.com.mvpshop.view.PlusView;    /**     * Created by Adminjs on 2017/11/21.     */    public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.IViewHolder> {        private Context context;        private List<ShopBean.DataBean.ListBean> list;        // 存放 商家的id 和 商家名称        private Map<String,String> map = new HashMap<>();        public ShopAdapter(Context context) {            this.context = context;            ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context));        }        /**         * 添加数据 并更新显示         * @param bean         */        public void add(ShopBean bean) {            if (this.list == null) {                this.list = new ArrayList<>();            }            // 遍历商家            for (ShopBean.DataBean shop : bean.getData()) {                map.put(shop.getSellerid(),shop.getSellerName());                // 遍历商品                for (int i = 0; i < shop.getList().size(); i++) {                    this.list.add(shop.getList().get(i));                }            }            setFirst(this.list);            notifyDataSetChanged();        }        /**         * 设置数据源, 控制显示商家         * @param list         */        private void setFirst(List<ShopBean.DataBean.ListBean> list){            if(list.size() > 0){                list.get(0).setIsFirst(1);                for(int i=1;i<list.size();i++){                    if(list.get(i).getSellerid() == list.get(i-1).getSellerid()){                        list.get(i).setIsFirst(2);                    }else{                        list.get(i).setIsFirst(1);                         if (list.get(i).isItemSelected()){                     list.get(i).setShopSelected(list.get(i).isItemSelected());                }                    }                }            }        }        @Override        public ShopAdapter.IViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {            View view = View.inflate(context, R.layout.adapter_layout, null);            return new IViewHolder(view);        }        @Override        public void onBindViewHolder(final ShopAdapter.IViewHolder holder, final int position) {            // 显示商品图片            if(list.get(position).getIsFirst() == 1){                //显示商家                holder.shop_checkbox.setVisibility(View.VISIBLE);                holder.tvItemShopcartShopname.setVisibility(View.VISIBLE);                holder.shop_checkbox.setChecked(list.get(position).isShopSelected());    //            显示商家的名称    //            list.get(position).getSellerid() 取到商家的id    //            map.get()取到 商家的名称                holder.tvItemShopcartShopname.setText(map.get(String.valueOf(list.get(position).getSellerid())));            } else {                holder.shop_checkbox.setVisibility(View.GONE);                holder.tvItemShopcartShopname.setVisibility(View.GONE);            }            //控制 商品的  checkbox            holder.item_checkbox.setChecked(list.get(position).isItemSelected());            String[] url = list.get(position).getImages().split("\|");            ImageLoader.getInstance().displayImage(url[0],holder.item_pic);            holder.item_name.setText(list.get(position).getTitle());            holder.item_price.setText(list.get(position).getPrice()+"");            holder.plusViewId.setEditText(list.get(position).getNum());            // 商家的checkbox            holder.shop_checkbox.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View view) {                    list.get(position).setShopSelected(holder.shop_checkbox.isChecked());                    for(int i=0;i<list.size();i++){                        if(list.get(position).getSellerid() == list.get(i).getSellerid()){                            list.get(i).setItemSelected(holder.shop_checkbox.isChecked());                        }                    }                    notifyDataSetChanged();                    sum(list);                }            });            // 商品的checkbox            holder.item_checkbox.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View view) {                    list.get(position).setItemSelected(holder.item_checkbox.isChecked());                    for(int i=0;i<list.size();i++){                        for (int j=0;j<list.size();j++){                            if(list.get(i).getSellerid() == list.get(j).getSellerid() && !list.get(j).isItemSelected()){                                list.get(i).setShopSelected(false);                                break;                            }else {                                list.get(i).setShopSelected(true);                            }                        }                    }                    notifyDataSetChanged();                    sum(list);                }            });            holder.item_del.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View view) {                    list.remove(position);                    setFirst(list);                    notifyDataSetChanged();                    sum(list);                }            });            //加减号            holder.plusViewId.setListener(new PlusView.ClickListener() {                @Override                public void click(int count) {                    list.get(position).setNum(count);                    notifyDataSetChanged();                    sum(list);                }            });        }        @Override        public int getItemCount() {            return list == null ? 0 : list.size();        }        /**         * 计算总价         * @param list         */        private void sum(List<ShopBean.DataBean.ListBean> list){            int totalNum = 0 ;            float totalMoney =  0.0f;            boolean allCheck =true;            for(int i=0;i<list.size();i++){                if(list.get(i).isItemSelected()){                    totalNum += list.get(i).getNum() ;                    totalMoney += list.get(i).getNum() * list.get(i).getPrice();                }else {                    allCheck = false;                }            }            listener.setTotal(totalMoney+"",totalNum+"",allCheck);        }        public void selectAll(boolean check){            for(int i=0;i<list.size();i++){                list.get(i).setShopSelected(check);                list.get(i).setItemSelected(check);            }            notifyDataSetChanged();            sum(list);        }        static class IViewHolder extends RecyclerView.ViewHolder {            @BindView(R.id.view)            View view;            @BindView(R.id.shop_checkbox)            CheckBox shop_checkbox;            @BindView(R.id.tv_item_shopcart_shopname)            TextView tvItemShopcartShopname;            @BindView(R.id.ll_shopcart_header)            LinearLayout llShopcartHeader;            @BindView(R.id.item_checkbox)            CheckBox item_checkbox;            @BindView(R.id.item_pic)            ImageView item_pic;            @BindView(R.id.item_price)            TextView item_price;            @BindView(R.id.item_name)            TextView item_name;            @BindView(R.id.tv_item_shopcart_cloth_size)            TextView tvItemShopcartClothSize;            @BindView(R.id.plus_view_id)            PlusView plusViewId;            @BindView(R.id.item_del)            ImageView item_del;            IViewHolder(View view) {                super(view);                ButterKnife.bind(this, view);            }        }        public UpdateUiListener listener;        public void setListener(UpdateUiListener listener){            this.listener = listener;        }        public interface UpdateUiListener {            public void setTotal(String total,String num,boolean allCheck);        }    }

MainActivity

    package gouwuche.bwei.com.mvpshop.activity;    import android.app.Activity;    import android.os.Bundle;    import android.support.v7.widget.LinearLayoutManager;    import android.support.v7.widget.RecyclerView;    import android.util.Log;    import android.widget.CheckBox;    import android.widget.LinearLayout;    import android.widget.TextView;    import android.widget.Toast;    import butterknife.BindView;    import butterknife.ButterKnife;    import butterknife.OnClick;    import gouwuche.bwei.com.mvpshop.R;    import gouwuche.bwei.com.mvpshop.adapter.ShopAdapter;    import gouwuche.bwei.com.mvpshop.bean.ShopBean;    import gouwuche.bwei.com.mvpshop.presenter.MainPresenter;    import gouwuche.bwei.com.mvpshop.view.MainViewListener;    public class MainActivity extends Activity implements MainViewListener {        @BindView(R.id.third_recyclerview)        RecyclerView thirdRecyclerview;        @BindView(R.id.third_allselect)        CheckBox checkBoxAll;        @BindView(R.id.third_totalprice)        TextView thirdTotalprice;        @BindView(R.id.third_totalnum)        TextView thirdTotalnum;        @BindView(R.id.third_submit)        TextView thirdSubmit;        @BindView(R.id.third_pay_linear)        LinearLayout thirdPayLinear;        private MainPresenter presenter;        private ShopAdapter adapter;        @Override        protected void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            setContentView(R.layout.activity_main);            ButterKnife.bind(this);            presenter = new MainPresenter(this);            presenter.getData();            adapter = new ShopAdapter(this);            LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);            thirdRecyclerview.setLayoutManager(manager);            thirdRecyclerview.setAdapter(adapter);            adapter.setListener(new ShopAdapter.UpdateUiListener() {                @Override                public void setTotal(String total, String num,boolean allCheck) {                    checkBoxAll.setChecked(allCheck);                    thirdTotalnum.setText(num);                    thirdTotalprice.setText(total);                }            });        }        @Override        public void success(ShopBean bean) {            Log.i("mean",bean.toString());            adapter.add(bean);        }        @Override        public void failure(Exception e) {            Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();        }        @Override        protected void onDestroy() {            super.onDestroy();            presenter.detach();        }        @OnClick(R.id.third_allselect)        public void onViewClicked() {            adapter.selectAll(checkBoxAll.isChecked());        }    }

ShopBean

    package gouwuche.bwei.com.mvpshop.bean;import java.util.List;/** * Created by Adminjs on 2017/11/21. */public class ShopBean {    private String msg;    private String code;    private List<DataBean> data;    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    public String getCode() {        return code;    }    public void setCode(String code) {        this.code = code;    }    public List<DataBean> getData() {        return data;    }    public void setData(List<DataBean> data) {        this.data = data;    }    public static class DataBean {      private String sellerName;        private String sellerid;        private List<ListBean> list;        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;        }        public List<ListBean> getList() {            return list;        }        public void setList(List<ListBean> list) {            this.list = list;        }        public static class ListBean {            /**             * bargainPrice : 22.9             * createtime : 2017-10-14T21:48:08             * detailUrl : https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends             * images : https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg             * num : 2             * pid : 24             * price : 288.0             * pscid : 2             * selected : 0             * sellerid : 1             * subhead : 三只松鼠零食特惠,专区满99减50,满199减100,火速抢购》             * title : 三只松鼠 坚果炒货 零食奶油味 碧根果225g/袋             */            private double bargainPrice;            private String createtime;            private String detailUrl;            private String images;            private int num;            private int pid;            private double price;            private int pscid;            private int selected;            private int sellerid;            private String subhead;            private String title;            // 1 显示商家  2 隐藏商家            private int isFirst;            // true 表示商家选中 false 相反            private boolean shopSelected;            // true 表示 当前商品是选中的 false 相反            private boolean itemSelected;            public double getBargainPrice() {                return bargainPrice;            }            public void setBargainPrice(double bargainPrice) {                this.bargainPrice = bargainPrice;            }            public String getCreatetime() {                return createtime;            }            public void setCreatetime(String createtime) {                this.createtime = createtime;            }            public String getDetailUrl() {                return detailUrl;            }            public void setDetailUrl(String detailUrl) {                this.detailUrl = detailUrl;            }            public String getImages() {                return images;            }            public void setImages(String 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() {                return price;            }            public void setPrice(double price) {                this.price = price;            }            public int getPscid() {                return pscid;            }            public void setPscid(int pscid) {                this.pscid = pscid;            }            public int getSelected() {                return selected;            }            public void setSelected(int selected) {                this.selected = selected;            }            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() {                return title;            }            public void setTitle(String title) {                this.title = title;            }            public int getIsFirst() {                return isFirst;            }            public void setIsFirst(int isFirst) {                this.isFirst = isFirst;            }            public boolean isShopSelected() {                return shopSelected;            }            public void setShopSelected(boolean shopSelected) {                this.shopSelected = shopSelected;            }            public boolean isItemSelected() {                return itemSelected;            }            public void setItemSelected(boolean itemSelected) {                this.itemSelected = itemSelected;            }        }    }}

源码下载

原创粉丝点击