OkHttp+listview+MVP购物车

依赖:
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.squareup.okhttp3:okhttp:3.10.0'
权限:
<uses-permission android:name="android.permission.INTERNET"/>


	工具类
public class OkHttpsUtils {

    private OkHttpsUtils(){};
    static OkHttpClient client;

    public static OkHttpClient getInstance(){
        if (client==null){
            synchronized (OkHttpsUtils.class){
                File file = new File(Environment.getExternalStorageDirectory(),"cache1");
                client = new OkHttpClient().newBuilder()
                        .readTimeout(3000, TimeUnit.SECONDS)
                        .connectTimeout(3000,TimeUnit.SECONDS)
                        .cache(new Cache(file,10*1024))
                        .build();
            }
        }
        return client;
    }


    public static void doget(String url, Callback callback){
        OkHttpClient client = getInstance();
        Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(callback);
    }


    public static void dopost(String url, Map<String,String> parms,Callback callback){
        OkHttpClient client = getInstance();

        FormBody.Builder body = new FormBody.Builder();

        for (String key:parms.keySet()){
            body.add(key,parms.get(key));
        }
        Request request = new Request.Builder()
                .url(url)
                .post(body.build())
                .build();
        client.newCall(request).enqueue(callback);
    }

    public static void upImage(String url,File file,String filenName,Map<String,String> params,Callback callback){
        OkHttpClient client = getInstance();
        MultipartBody.Builder builder = new MultipartBody.Builder();

        if (params==null){
            for (String key:params.keySet()){
                builder.addFormDataPart(key,params.get(key));
            }
        }

        builder.setType(MultipartBody.FORM);

        builder.addFormDataPart("file",filenName, RequestBody.create(MediaType.parse("application/octet-stream"),file));

        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        client.newCall(request).enqueue(callback);
    }

}



	MainActivity布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.whk.one.view.MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lv"
        android:layout_weight="1"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全选"
            android:id="@+id/cb"
            android:layout_weight="1"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/hj"
            android:layout_weight="1"
            android:text="合计"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="结算"
            android:id="@+id/js"/>
    </LinearLayout>

</LinearLayout>
	
	子条目布局	
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="90dp">
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="90dp"
        android:id="@+id/item_cb"/>
    <ImageView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id="@+id/item_pic"
        android:layout_toRightOf="@+id/item_cb"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/item_title"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@id/item_pic"
        android:text="aaa"/>
    <TextView
        android:textColor="#f00"
        android:layout_marginLeft="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/item_jg"
        android:layout_toRightOf="@id/item_pic"
        android:layout_marginTop="35dp"
        android:text="bbb"
        />
    <Button
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:text="-"
        android:layout_marginLeft="20dp"
        android:id="@+id/item_jian"
        android:layout_toRightOf="@id/item_pic"
    android:layout_alignBottom="@id/item_pic"/>
    <TextView
        android:textColor="#f0f"
        android:gravity="center"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/item_num"
        android:layout_alignBottom="@id/item_pic"
        android:layout_toRightOf="@id/item_jian"
        android:text="ccc"
        />
    <Button
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:text="+"
        android:id="@+id/item_jia"
        android:layout_toRightOf="@id/item_num"
        android:layout_alignBottom="@id/item_pic"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/sc"
        android:text="删除"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

	modle类
 
public interface DateModel {
    void getVdate(String url, DatePrementer datePrementer);
}
	modle实现类
public class MyDateModel implements DateModel {
    @Override
    public void getVdate(String url, final DatePrementer datePrementer) {
        OkHttpsUtils.doget(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                DateBeans dateBeans = gson.fromJson(string, DateBeans.class);
                List<DateBeans.DataBean> list = dateBeans.getData();
                datePrementer.succes(list);
            }
        });
    }
}

 
	presenter类
 
public interface DatePrementer {
    void succes(List<DateBeans.DataBean> list);
    void error();
}

	
	
	presenter实现类
public class MyDatePrementer implements DatePrementer {
    DataView dataView;
    private final MyDateModel myDateModel;
	
//提供构造方法
    public  MyDatePrementer(DataView dataView){
        this.dataView=dataView;
        myDateModel = new MyDateModel();
    }
	
	
    @Override
    public void succes(List<DateBeans.DataBean> list) {
	//成功时把数据传给V层
        dataView.getMdate(list);
    }

    @Override
    public void error() {

    }
	
	//通过v层传来的url得到请求的数据
    public void getUrl(String url){
        myDateModel.getVdate(url,this);
    }
}

	Dataview类
public interface DataView {
	//请求数据方法
    void getMdate(List<DateBeans.DataBean> list);
}

	
	
	Dataview实现类
MainActivity
public class MainActivity extends AppCompatActivity implements DataView,MyAdapter.ChangeDate{
    String dataUrl = "https://www.zhaoapi.cn/product/getProducts?pscid=1";
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            list = (List<DateBeans.DataBean>) msg.obj;
            //Log.i("----", "handleMessage: "+list.size());
            adapter = new MyAdapter(MainActivity.this, list);
            lv.setAdapter(adapter);
            adapter.ChangeNum(MainActivity.this);
        }
    };
    private ListView lv;

    private double dPrice;
    private List<DateBeans.DataBean> list;
    private MyAdapter adapter;
    private TextView hj;
    private CheckBox cb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
		//得到p层对象
        MyDatePrementer myDatePrementer = new MyDatePrementer(this);
        myDatePrementer.getUrl(dataUrl);

        hj = findViewById(R.id.hj);
        lv = findViewById(R.id.lv);
        cb = findViewById(R.id.cb);
		//给复选框设置监听
        cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb.isChecked()){
                     for (int i = 0; i < list.size(); i++) {
                        list.get(i).setCheck(true);
                    }
                }else {
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setCheck(false);
                    }
                }
		//调用总价方法
                getZj();
                adapter.notifyDataSetChanged();
            }
        });
    }
	//把请求的数据发给handler
    @Override
    public void getMdate(List<DateBeans.DataBean> list) {
        Message msg = Message.obtain();
        //Message msg = new Message();
        msg.obj=list;
	//发送消息
        handler.sendMessage(msg);
    }
	
	//数量加方法
    @Override
    public void jia(int position) {
        DateBeans.DataBean dataBean = list.get(position);
        int sellerid = dataBean.getSellerid();
        sellerid++;
        dataBean.setSellerid(sellerid);
        getZj();
        adapter.notifyDataSetChanged();

    }
	//数量减方法
    @Override
    public void jian(int position) {
        DateBeans.DataBean dataBean = list.get(position);
        int sellerid = dataBean.getSellerid();
        if (sellerid==1){
            return;
        }
        sellerid--;
        list.get(position).setSellerid(sellerid);
        getZj();
        adapter.notifyDataSetChanged();

    }
	
	//复选框是否选中
    @Override
    public void cbCheack(int position, boolean checked) {
        list.get(position).setCheck(checked);
        getZj();
        adapter.notifyDataSetChanged();
    }
	
	//删除条目方法
    @Override
    public void sc(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("警告!");
        builder.setMessage("确定要删除订单吗?");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                list.remove(position);
                getZj();
                adapter.notifyDataSetChanged();
            }
        });
        builder.show();
    }

	//总价方法
    public void getZj(){
        dPrice=0;
        for (int i = 0; i < list.size(); i++) {
            DateBeans.DataBean dataBean = list.get(i);
            if (dataBean.isCheck()){
                dPrice+=dataBean.getPrice()*dataBean.getSellerid();
            }

        }
        adapter.notifyDataSetChanged();
        hj.setText("合计:"+new DecimalFormat("0.00").format(dPrice));

    }
}

	适配器
public class MyAdapter extends BaseAdapter{
    Context context;
    List<DateBeans.DataBean> list;
    ChangeDate changeDate;
    public MyAdapter(Context context, List<DateBeans.DataBean> list) {
        this.context=context;
        this.list=list;
    }

    //得到接口对象
    public void ChangeNum(ChangeDate changeDate){
        this.changeDate=changeDate;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder;
        if (convertView==null){
            convertView=View.inflate(context, R.layout.item_view,null);
            holder=new ViewHolder();
            holder.cb=convertView.findViewById(R.id.item_cb);
            holder.pic=convertView.findViewById(R.id.item_pic);
            holder.title=convertView.findViewById(R.id.item_title);
            holder.sl=convertView.findViewById(R.id.item_num);
            holder.jg=convertView.findViewById(R.id.item_jg);
            holder.jia=convertView.findViewById(R.id.item_jia);
            holder.jian=convertView.findViewById(R.id.item_jian);
            holder.sc=convertView.findViewById(R.id.sc);
            convertView.setTag(holder);
        }else {
            holder= (ViewHolder) convertView.getTag();
        }

        holder.title.setText(list.get(position).getTitle());
        holder.jg.setText(list.get(position).getPrice()+"");
        Glide.with(context).load(list.get(position).getImages().split("\\|")[0]).into(holder.pic);
        holder.sl.setText(list.get(position).getSellerid()+"");

        holder.cb.setChecked(list.get(position).isCheck());

        holder.sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeDate.sc(position);
            }
        });

        holder.cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.get(position).setCheck(holder.cb.isChecked());
                changeDate.cbCheack(position,holder.cb.isChecked());
            }
        });

        holder.jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeDate.jia(position);
            }
        });

        holder.jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeDate.jian(position);
            }
        });


        return convertView;
    }
    class ViewHolder{
        TextView jg,title,sl;
        ImageView pic;
        Button jia,jian,sc;
        CheckBox cb;
    }

    public interface ChangeDate{
        void jia(int position);
        void jian(int position);
        void cbCheack(int position, boolean checked);
        void sc(int position);
    }
}


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值