购物车+自定义拦截器

来源:互联网 发布:lol免费皮肤软件 编辑:程序博客网 时间:2024/05/29 10:22

activity_main

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"   >    <com.liaoinstan.springview.widget.SpringView        android:layout_width="match_parent"        android:id="@+id/springview"        android:layout_weight="1"        android:layout_height="0dp">        <android.support.v7.widget.RecyclerView            android:layout_width="match_parent"            android:layout_height="match_parent"            android:id="@+id/recyclerview"       >        </android.support.v7.widget.RecyclerView>    </com.liaoinstan.springview.widget.SpringView>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        >        <CheckBox            android:id="@+id/allselect"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="全选"            />        <LinearLayout            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:orientation="vertical"            >            <TextView                android:id="@+id/totalprice"                android:layout_width="200dp"                android:layout_height="wrap_content"                android:text="总价:"                />            <TextView                android:id="@+id/totalnum"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="共0件商品"                />        </LinearLayout>        <TextView            android:id="@+id/third_submit"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="去结算"            android:textColor="#000000"            />    </LinearLayout></LinearLayout>
customerview布局
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal">    <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/edtext"/>    <Button        android:background="#00FFFFFF"        android:text="+"        android:id="@+id/add"        android:layout_width="10dp"        android:layout_height="wrap_content"/></LinearLayout>

layout_adapter


<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#ffffff"    android:orientation="vertical">    <LinearLayout        android:layout_width="match_parent"        android:gravity="center_vertical"        android:layout_height="wrap_content">        <CheckBox            android:id="@+id/shop_check"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:checked="false" />        <TextView            android:id="@+id/shop_name"            android:text="商户名称"            android:layout_marginLeft="10dp"            android:textSize="20sp"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />    </LinearLayout>    <LinearLayout        android:layout_marginLeft="30dp"        android:layout_width="match_parent"        android:gravity="center_vertical"        android:layout_height="wrap_content">        <CheckBox            android:id="@+id/checkbox"            android:layout_gravity="center_vertical"            android:layout_weight="0"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <ImageView            android:id="@+id/shopface"            android:layout_width="100dp"            android:layout_height="100dp"            android:src="@mipmap/ic_launcher"/>        <LinearLayout            android:layout_weight="1"            android:layout_width="0dp"            android:layout_height="196dp"            android:gravity="center_vertical"            android:orientation="vertical">            <TextView                android:id="@+id/shoptitle"                android:layout_marginLeft="10dp"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="商品信息"/>            <TextView                android:id="@+id/shopprice"                android:layout_marginTop="10dp"                android:layout_marginLeft="10dp"                android:textColor="#f00"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="商品价格"/>            <com.bwie.CoustomView                android:id="@+id/coustomview"                android:layout_width="wrap_content"                android:layout_marginTop="10dp"                android:layout_marginLeft="10dp"                android:layout_height="wrap_content">            </com.bwie.CoustomView>        </LinearLayout>        <Button            android:id="@+id/shopdel"            android:layout_weight="0"            android:layout_gravity="center_vertical"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="删除"          />    </LinearLayout></LinearLayout>
Mactivity


package com.bwie.lenovo.mvpshop;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.View;import android.widget.CheckBox;import android.widget.TextView;import com.bwie.lenovo.mvpshop.adapter.ShopAdapter;import com.bwie.lenovo.mvpshop.bean.ShopBean;import com.bwie.lenovo.mvpshop.presenter.MyPresenter;import com.bwie.lenovo.mvpshop.view.MyView;import com.liaoinstan.springview.container.DefaultFooter;import com.liaoinstan.springview.container.DefaultHeader;import com.liaoinstan.springview.widget.SpringView;public class MainActivity extends AppCompatActivity implements MyView {    private RecyclerView mRecyclerView;    private CheckBox mAllselect;    private TextView mTotalprice;    private TextView mTotalnum;    private TextView mSubmitThird;    private ShopAdapter shopAdapter;    private MyPresenter myPresenter;    private SpringView springView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        myPresenter = new MyPresenter(this, this);        myPresenter.MyPresenter("http://120.27.23.105/product/getCarts?uid=100");        //布局管理器        LinearLayoutManager manager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);        mRecyclerView.setLayoutManager(manager);        mAllselect.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                shopAdapter.selectAll(mAllselect.isChecked());            }        });        springView.setHeader(new DefaultHeader(MainActivity.this));        springView.setFooter(new DefaultFooter(MainActivity.this));        springView.setListener(new SpringView.OnFreshListener() {            @Override            public void onRefresh() {                springView.onFinishFreshAndLoad();            }            @Override            public void onLoadmore() {                springView.onFinishFreshAndLoad();            }        });    }    private void initView() {        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);        mAllselect = (CheckBox) findViewById(R.id.allselect);        mTotalprice = (TextView) findViewById(R.id.totalprice);        mTotalnum = (TextView) findViewById(R.id.totalnum);        mSubmitThird = (TextView) findViewById(R.id.third_submit);        springView= (SpringView) findViewById(R.id.springview);    }    @Override    public void getData(final ShopBean shopBean) {        runOnUiThread(new Runnable() {            @Override            public void run() {                shopAdapter = new ShopAdapter(MainActivity.this,shopBean);                mRecyclerView.setAdapter(shopAdapter);                shopAdapter.setListener(new ShopAdapter.UpdateUiListener() {                    @Override                    public void setTotal(String total, String num, boolean allCheck) {                        mAllselect.setChecked(allCheck);                        mTotalnum.setText(num);                        mTotalprice.setText(total);                    }                });            }        });    }    //内存泄漏    @Override    protected void onDestroy() {        super.onDestroy();        myPresenter.deatch();    }}
Model接口

package com.bwie.lenovo.mvpshop.model;import okhttp3.Callback;/** * Created by lenovo on 2017/11/21. */public interface IModel {    public  void initData(String path, Callback callback);}

Model实现接口的类

package com.bwie.lenovo.mvpshop.model;import com.bwie.lenovo.mvpshop.utils.OkHttp3Utils;import okhttp3.Callback;/** * Created by lenovo on 2017/11/21. */public class MyModel implements IModel {    @Override    public void initData(String path, Callback callback) {        OkHttp3Utils.doGet(path,callback);    }}
View接口

package com.bwie.lenovo.mvpshop.view;import com.bwie.lenovo.mvpshop.bean.ShopBean;/** * Created by lenovo on 2017/11/21. */public interface  MyView {    public  void getData(ShopBean shopBean);}

Presenter类

package com.bwie.lenovo.mvpshop.presenter;import android.content.Context;import com.bwie.lenovo.mvpshop.bean.ShopBean;import com.bwie.lenovo.mvpshop.model.MyModel;import com.bwie.lenovo.mvpshop.utils.OnUiCallback;import com.bwie.lenovo.mvpshop.view.MyView;import com.google.gson.Gson;import java.io.IOException;import okhttp3.Call;/** * Created by lenovo on 2017/11/21. */public class MyPresenter {    Context context;    MyView myView;    MyModel myModel;    public MyPresenter(Context context, MyView myView) {        this.context = context;        this.myView = myView;        this.myModel = new MyModel();    }    public  void  MyPresenter(String path){        myModel.initData(path, new OnUiCallback() {            @Override            public void onFailed(Call call, IOException e) {            }            @Override            public void onSuccess(String result) {                Gson gson=new Gson();                ShopBean shopBean=gson.fromJson(result, ShopBean.class);                myView.getData(shopBean);            }        });    }    public  void  deatch(){        myView=null;    }}
其中applaction中有ImagelLOader两个类

还有utils

拦截器LoggingInterceptor 

package com.bwie.lenovo.mvpshop.utils;import java.io.IOException;import okhttp3.FormBody;import okhttp3.Interceptor;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;/** * Created by lenovo on 2017/11/22. */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=new Request.Builder();            builder.get().url(url);            requestprocess=builder.build();            System.out.println(requestprocess);            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;    }}

CustomerView类

package com.bwie;import android.content.Context;import android.util.AttributeSet;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import com.bwie.lenovo.mvpshop.R;/** * Created by lenovo on 2017/11/21. */public class CoustomView extends LinearLayout{    Context context;    private Button revserse;    private Button add;    private EditText editText;   private  int mcount=1;    public CoustomView(Context context) {        super(context);    }    public CoustomView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    public CoustomView(Context context, AttributeSet attrs) {        super(context, attrs);        View view= View.inflate(context, R.layout.customerview,null);        revserse = (Button) view.findViewById(R.id.revserse);        add = (Button) view.findViewById(R.id.add);        editText = (EditText) view.findViewById(R.id.edtext);        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 (lisenter!=null){                            lisenter.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(mcount+"");                        if (lisenter!=null){                            lisenter.click(mcount);                        }                } 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 void setEditText(int num){        if (editText!=null){            editText.setText(num+"");        }    }    private ClickLisenter lisenter;    public void setListener(ClickLisenter lisenter){        this.lisenter=lisenter;    }    public interface ClickLisenter{        public void click(int count);    }}

Adapter类

package com.bwie.lenovo.mvpshop.adapter;import android.content.Context;import android.support.v7.widget.RecyclerView;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.CheckBox;import android.widget.ImageView;import android.widget.TextView;import com.bwie.CoustomView;import com.bwie.lenovo.mvpshop.R;import com.bwie.lenovo.mvpshop.bean.ShopBean;import com.nostra13.universalimageloader.core.ImageLoader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/** * Created by lenovo on 2017/11/21. */public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.ViewHolder>{    Context context;    private List<ShopBean.DataBean.ListBean> list;    // 存放 商家的id 和 商家名称    private Map<String,String> map = new HashMap<>();    public ShopAdapter(Context context, ShopBean shopBean) {        this.context = context;        add(shopBean);    }    /**     * 添加数据 并更新显示     * @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());                    }                }            }        }    }    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        View view = View.inflate(context, R.layout.layout_adapter, null);        return new ViewHolder(view);    }    public void onBindViewHolder(final ViewHolder holder, final int position) {        // 显示商品图片        if(list.get(position).getIsFirst() == 1){            //显示商家            holder.mCheckShop.setVisibility(View.VISIBLE);            holder.mNameShop.setVisibility(View.VISIBLE);            holder.mCheckShop.setChecked(list.get(position).isShopSelected());//            显示商家的名称//            list.get(position).getSellerid() 取到商家的id//            map.get()取到 商家的名称            holder.mNameShop.setText(map.get(String.valueOf(list.get(position).getSellerid())));        } else {            holder.mCheckShop.setVisibility(View.GONE);            holder.mNameShop.setVisibility(View.GONE);        }        String[] url = list.get(position).getImages().split("\\|");        ImageLoader.getInstance().displayImage(url[0],holder.mShopface);        holder.mShoptitle.setText(list.get(position).getTitle());        holder.mShopprice.setText(list.get(position).getPrice()+"");        holder.mCheckShop.setChecked(list.get(position).isShopSelected());        holder.mCheckbox.setChecked(list.get(position).isItemSelected());        holder.mCoustomview.setEditText(list.get(position).getNum());        //删除        holder.mShopdel.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                list.remove(position);                setFirst(list);                notifyDataSetChanged();                sum(list);            }        });        //调用Coustomview的接口        holder.mCoustomview.setListener(new CoustomView.ClickLisenter() {            @Override            public void click(int count) {                list.get(position).setNum(count);                notifyDataSetChanged();                sum(list);            }        });        //商家的CheckBox       holder.mCheckShop.setOnClickListener(new View.OnClickListener() {           @Override           public void onClick(View view) {             list.get(position).setShopSelected(holder.mCheckShop.isChecked());               for(int i=0;i<list.size();i++){                   if (list.get(position).getSellerid()==list.get(i).getSellerid()){                       list.get(i).setItemSelected(holder.mCheckShop.isChecked());                   }               }               notifyDataSetChanged();               sum(list);           }       });        //商品的CheckBox        holder.mCheckbox.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                list.get(position).setItemSelected(holder.mCheckbox.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.plusViewId.setEditText(list.get(position).getNum());    }    //计算总价    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);    }    public int getItemCount() {        return list == null ? 0 : list.size();    }    public class ViewHolder extends RecyclerView.ViewHolder {        private CheckBox mCheckShop;        private TextView mNameShop;        private CheckBox mCheckbox;        private ImageView mShopface;        private TextView mShoptitle;        private TextView mShopprice;        private CoustomView mCoustomview;        private Button mShopdel;        public ViewHolder(View itemView) {            super(itemView);            mCheckShop = (CheckBox) itemView.findViewById(R.id.shop_check);            mNameShop = (TextView) itemView.findViewById(R.id.shop_name);            mCheckbox = (CheckBox) itemView.findViewById(R.id.checkbox);            mShopface = (ImageView) itemView.findViewById(R.id.shopface);            mShoptitle = (TextView) itemView.findViewById(R.id.shoptitle);            mShopprice = (TextView) itemView.findViewById(R.id.shopprice);            mCoustomview = (CoustomView) itemView.findViewById(R.id.coustomview);            mShopdel = (Button) itemView.findViewById(R.id.shopdel);        }    }    public UpdateUiListener listener;    public void setListener(UpdateUiListener listener){        this.listener = listener;    }    public interface UpdateUiListener {         void setTotal(String total,String num,boolean allCheck);    }}

原创粉丝点击