一级购物车逻辑

本文介绍如何在MVP架构中运用OkHttp进行网络请求,并通过Gson解析JSON数据,实现商品信息的展示与交互功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//依赖
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
compile 'org.greenrobot:eventbus:3.1.1'
//okhttp
package mvpframework.bwie.com.myyjgw.net;

import java.util.Map;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;

public class HttpUtils {
    private static HttpUtils httpUtils;
    private final OkHttpClient client;

    private HttpUtils(){
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();
    }
    public static HttpUtils getHttpUtils(){
        if (httpUtils==null){
            synchronized (HttpUtils.class){
                if (httpUtils==null){
                    httpUtils = new HttpUtils();
                }
            }
        }
        return httpUtils;
    }
    public void doGet(String url, Callback callback){
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(callback);
    }
    public void doPost(String url, Map<String,String> params,Callback callback){
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String ,String> entry:params.entrySet()){
            builder.add(entry.getKey(),entry.getValue());
        }
        FormBody build = builder.build();
        Request request = new Request.Builder().url(url).post(build).build();
        client.newCall(request).enqueue(callback);
    }
}

//api
package mvpframework.bwie.com.myyjgw.net;

public class Api {
    public static final String url="http://result.eolinker.com/iYXEPGn4e9c6dafce6e5cdd23287d2bb136ee7e9194d3e9?uri=evaluation";
}
//OnNetlistener
package mvpframework.bwie.com.myyjgw.net;

import java.io.IOError;
import java.io.IOException;

public interface OnNetlistener<T> {
    public void onSuccess(T t);
    public void onError(IOException e);
}
//model层
package mvpframework.bwie.com.myyjgw.model;

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;

import java.io.IOException;

import mvpframework.bwie.com.myyjgw.bean.PhoneBean;
import mvpframework.bwie.com.myyjgw.net.Api;
import mvpframework.bwie.com.myyjgw.net.HttpUtils;
import mvpframework.bwie.com.myyjgw.net.OnNetlistener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PhoneModel implements IPhoneModel{
    private Handler handler=new Handler(Looper.getMainLooper());
    @Override
    public void getPhone(final OnNetlistener<PhoneBean> onNetlistener){
        HttpUtils.getHttpUtils().doGet(Api.url, new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetlistener.onError(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final PhoneBean phoneBean = new Gson().fromJson(string, PhoneBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetlistener.onSuccess(phoneBean);
                    }
                });
            }
        });
    }
}
------------接口----------------
package mvpframework.bwie.com.myyjgw.model;

import mvpframework.bwie.com.myyjgw.bean.PhoneBean;
import mvpframework.bwie.com.myyjgw.net.OnNetlistener;

public interface IPhoneModel {
    public void getPhone(OnNetlistener<PhoneBean> onNetlistener);

}
//view层
package mvpframework.bwie.com.myyjgw.view;

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.ExpandableListView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import mvpframework.bwie.com.myyjgw.Adpter.MyAdpter;
import mvpframework.bwie.com.myyjgw.R;
import mvpframework.bwie.com.myyjgw.bean.PhoneBean;
import mvpframework.bwie.com.myyjgw.eventbusevent.MessageEvent;
import mvpframework.bwie.com.myyjgw.eventbusevent.PriceAndCountEvent;
import mvpframework.bwie.com.myyjgw.presenter.PhonePresenter;

public class MainActivity extends AppCompatActivity implements IMainActivity{

    private ExpandableListView elv;
    private RecyclerView mRv;
    private CheckBox mCb;
    private TextView mTv_price;
    private TextView mTv_num;
    private MyAdpter myAdpter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        PhonePresenter presenter = new PhonePresenter(this);
        presenter.getPhone();
        initView();
        mRv.setLayoutManager(new LinearLayoutManager(this));
        //请求接口
        mCb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAdpter.allSelect(mCb.isChecked());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
     @Subscribe
     public void onMessageEvent(MessageEvent event){
         mCb.setChecked(event.isChecked());
     }
    @Subscribe
    public void onMessageEvent(PriceAndCountEvent event){
        mTv_num.setText("结算("+event.getCount()+")");
        mTv_price.setText(event.getPrice()+"");
    }
    private void initView() {
        mRv = (RecyclerView) findViewById(R.id.rv);
        mCb = (CheckBox) findViewById(R.id.checkbox2);
        mTv_price = (TextView) findViewById(R.id.tv_price);
        mTv_num = (TextView) findViewById(R.id.tv_num);
    }

    @Override
    public void getPhone(List<PhoneBean.DataBean.DatasBean> list) {
        myAdpter = new MyAdpter(list, this);
        mRv.setAdapter(myAdpter);
    }
}
------------------接口---------------------
package mvpframework.bwie.com.myyjgw.view;

import java.util.List;

import mvpframework.bwie.com.myyjgw.bean.PhoneBean;

public interface IMainActivity {
    public void getPhone(List<PhoneBean.DataBean.DatasBean> list);
}
//presenter层
package mvpframework.bwie.com.myyjgw.presenter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import mvpframework.bwie.com.myyjgw.bean.PhoneBean;
import mvpframework.bwie.com.myyjgw.model.IPhoneModel;
import mvpframework.bwie.com.myyjgw.model.PhoneModel;
import mvpframework.bwie.com.myyjgw.net.OnNetlistener;
import mvpframework.bwie.com.myyjgw.view.IMainActivity;
public class PhonePresenter {
    private IPhoneModel iPhoneModel;
    private final IMainActivity iMainActivity;
    public PhonePresenter(IMainActivity iMainActivity) {
        this.iMainActivity=iMainActivity;
        iPhoneModel= new PhoneModel();
    }
    public void getPhone(){
        iPhoneModel.getPhone(new OnNetlistener<PhoneBean>() {
            @Override
            public void onSuccess(PhoneBean phoneBean) {
                ArrayList<PhoneBean.DataBean.DatasBean> list = new ArrayList<>();
                List<PhoneBean.DataBean> data = phoneBean.getData();
                for (int i=0;i<data.size();i++){
                    List<PhoneBean.DataBean.DatasBean> datas = data.get(i).getDatas();
                    list.addAll(datas);

                }
                  iMainActivity.getPhone(list);
            }

            @Override
            public void onError(IOException e) {

            }
        });
    }
}
//自定义view(MyView)
package mvpframework.bwie.com.myyjgw;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MyView extends LinearLayout{

    private ImageView iv_del;
    private TextView tv_num;
    private ImageView iv_add;

    public MyView(Context context) {
        this(context,null);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        View view = LayoutInflater.from(context).inflate(R.layout.myview, this);
        iv_del = findViewById(R.id.iv_del);
        tv_num = findViewById(R.id.tv_num);
        iv_add = findViewById(R.id.iv_add);
    }
    public void setAddClickListener(OnClickListener onClickListener){
        iv_add.setOnClickListener(onClickListener);
    }
    public void setDelClickListener(OnClickListener onClickListener){
        iv_del.setOnClickListener(onClickListener);
    }
    public void setNum(String num){
        tv_num.setText(num);
    }
    public int getNum(){
        String num = tv_num.getText().toString();
        return Integer.parseInt(num);
    }
}

//适配器
package mvpframework.bwie.com.myyjgw.Adpter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import mvpframework.bwie.com.myyjgw.MyView;
import mvpframework.bwie.com.myyjgw.R;
import mvpframework.bwie.com.myyjgw.bean.PhoneBean;
import mvpframework.bwie.com.myyjgw.eventbusevent.MessageEvent;
import mvpframework.bwie.com.myyjgw.eventbusevent.PriceAndCountEvent;

public class MyAdpter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<PhoneBean.DataBean.DatasBean> list;
    private Context context;

    public MyAdpter(List<PhoneBean.DataBean.DatasBean> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.child, null);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        final PhoneBean.DataBean.DatasBean datasBean = list.get(position);
        final MyViewHolder myViewHolder = (MyViewHolder) holder;
        myViewHolder.cb_child.setChecked(datasBean.isChecked());
        myViewHolder.tv_tel.setText(datasBean.getType_name());
        myViewHolder.tv_content.setText(datasBean.getMsg());
        myViewHolder.tv_time.setText(datasBean.getAdd_time());
        myViewHolder.tv_pri.setText(datasBean.getPrice() + "");
        myViewHolder.myView.setNum(datasBean.getNum() + "");
        //checkbox点击事件
        myViewHolder.cb_child.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datasBean.setChecked(myViewHolder.cb_child.isChecked());
                PriceAndCountEvent priceAndCountEvent = compe();
                EventBus.getDefault().post(priceAndCountEvent);
                if (myViewHolder.cb_child.isChecked()){
                   if (isAllCbSelected()){
                       //改变全选状态
                         changeAllCbState(isAllCbSelected());
                   }
               }else {
                   changeAllCbState(isAllCbSelected());
               }
               notifyDataSetChanged();
            }
        });
        myViewHolder.myView.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num=myViewHolder.myView.getNum();
                num++;
                datasBean.setNum(num);
                if (myViewHolder.cb_child.isChecked()){
                    EventBus.getDefault().post(compe());
                }
                notifyDataSetChanged();
            }
        });
        myViewHolder.myView.setDelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num=myViewHolder.myView.getNum();
                if (num==1){
                    return;
                }
                num--;
                datasBean.setNum(num);
                if (myViewHolder.cb_child.isChecked()){
                    EventBus.getDefault().post(compe());
                }
                notifyDataSetChanged();
            }
        });
        myViewHolder.tv_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.remove(position);
                EventBus.getDefault().post(compe());
                notifyDataSetChanged();

            }
        });
    }

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

    class MyViewHolder extends RecyclerView.ViewHolder {

        private final CheckBox cb_child;
        private final TextView tv_tel;
        private final TextView tv_content;
        private final TextView tv_time;
        private final TextView tv_pri;
        private final TextView tv_del;
        private final MyView myView;

        public MyViewHolder(View itemView) {
            super(itemView);
            cb_child = itemView.findViewById(R.id.cb_child);
            tv_tel = itemView.findViewById(R.id.tv_tel);
            tv_content = itemView.findViewById(R.id.tv_content);
            tv_time = itemView.findViewById(R.id.tv_time);
            tv_pri = itemView.findViewById(R.id.tv_pri);
            tv_del = itemView.findViewById(R.id.tv_del);
            myView = itemView.findViewById(R.id.mv);
        }
    }

    //价格和数量
    private PriceAndCountEvent compe() {
        int count = 0;
        int price = 0;
        for (int i = 0; i < list.size(); i++) {
            PhoneBean.DataBean.DatasBean datasBean = list.get(i);
            if (datasBean.isChecked()) {
                price += datasBean.getPrice() * datasBean.getNum();
                count += datasBean.getNum();
            }
        }
        PriceAndCountEvent priceAndCountEvent = new PriceAndCountEvent();
        priceAndCountEvent.setCount(count);
        priceAndCountEvent.setPrice(price);
        return priceAndCountEvent;
    }
    private boolean  isAllCbSelected(){
        for (int i=0;i<list.size();i++){
            PhoneBean.DataBean.DatasBean datasBean = list.get(i);
            if (!datasBean.isChecked()){
                return false;
            }
        }
        return true;
    }
    private void changeAllCbState(boolean flag){
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setChecked(flag);
        EventBus.getDefault().post(messageEvent);
    }
    public void allSelect(boolean flag){
        for (int i=0;i<list.size();i++){
            PhoneBean.DataBean.DatasBean datasBean = list.get(i);
            datasBean.setChecked(flag);
        }
        EventBus.getDefault().post(compe());
        notifyDataSetChanged();
    }
}
//MessageEvent
package mvpframework.bwie.com.myyjgw.eventbusevent;

public class MessageEvent {
    private boolean checked;

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }
}
//PriceCountEvent
package mvpframework.bwie.com.myyjgw.eventbusevent;


public class PriceAndCountEvent {
    private int price;
    private int count;

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
//布局activity_main.xml
<?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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="mvpframework.bwie.com.myyjgw.view.MainActivity">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#990000ff"
        android:gravity="center"
        android:text="购物车"
        android:textColor="#ff3660"
        android:textSize="25sp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="@android:color/white"
        android:gravity="center_vertical">

        <CheckBox
            android:id="@+id/checkbox2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:focusable="false" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@+id/checkbox2"
            android:gravity="center_vertical"
            android:text="全选"
            android:textSize="20sp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="合计 :" />


            <TextView
                android:id="@+id/tv_price"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_marginLeft="10dp"
                android:paddingRight="10dp"
                android:text="0"
                android:textColor="@android:color/holo_red_light" />


            <TextView
                android:id="@+id/tv_num"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:background="@android:color/holo_red_dark"
                android:gravity="center"
                android:padding="10dp"
                android:text="结算(0)"
                android:textColor="@android:color/white" />
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>
//布局child.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"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <CheckBox

        android:id="@+id/cb_child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="30dp"
        android:focusable="false" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_tel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="iphone6" />

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="什么手机" />

        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="2016-12-10" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_pri"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="¥3000.00" />
        <mvpframework.bwie.com.myyjgw.MyView
            android:id="@+id/mv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"></mvpframework.bwie.com.myyjgw.MyView>
    </LinearLayout>

    <TextView
        android:id="@+id/tv_del"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除" />
</LinearLayout>
//myview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">


    <ImageView
        android:id="@+id/iv_del"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:src="@drawable/shopcart_minus_grey" />

    <TextView
        android:id="@+id/tv_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:background="@drawable/shopcart_add_btn"
        android:paddingBottom="2dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="2dp"
        android:text="1" />

    <ImageView
        android:id="@+id/iv_add"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginLeft="5dp"
        android:src="@drawable/shopcart_add_red" />

</LinearLayout>
//drawable下的shopcart_add_btn.xml和三个图片
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <corners android:radius="200dp"></corners>
    <stroke android:color="@color/colorPrimaryDark" android:width="1dp"></stroke>
</shape>

标题基于PHP + JavaScript的助眠小程序设计与实现AI更换标题第1章引言介绍助眠小程序的研究背景、意义,以及论文的研究内容和创新点。1.1研究背景与意义阐述助眠小程序在当前社会的重要性和应用价值。1.2国内外研究现状分析国内外在助眠小程序方面的研究进展及现状。1.3论文研究内容与创新点概述论文的主要研究内容和创新之处。第2章相关理论基础介绍助眠小程序设计与实现所涉及的相关理论基础。2.1PHP编程技术阐述PHP编程技术的基本概念、特点和在助眠小程序中的应用。2.2JavaScript编程技术介绍JavaScript编程技术的核心思想、作用及在小程序中的实现方式。2.3小程序设计原理讲解小程序的设计原则、架构和关键技术。第3章助眠小程序需求分析对助眠小程序进行详细的需求分析,为后续设计与实现奠定基础。3.1用户需求调研用户需求调研的过程和方法,总结用户需求。3.2功能需求分析根据用户需求,分析并确定助眠小程序的核心功能和辅助功能。3.3性能需求分析明确助眠小程序在性能方面的要求,如响应速度、稳定性等。第4章助眠小程序设计详细阐述助眠小程序的设计方案,包括整体架构、功能模块和界面设计。4.1整体架构设计给出助眠小程序的整体架构设计思路和实现方案。4.2功能模块设计详细介绍各个功能模块的设计思路和实现方法。4.3界面设计阐述助眠小程序的界面设计风格、布局和交互设计。第5章助眠小程序实现与测试讲解助眠小程序的实现过程,并进行详细的测试与分析。5.1开发环境搭建与配置介绍开发环境的搭建过程和相关配置信息。5.2代码实现与优化详细阐述助眠小程序的代码实现过程,包括关键技术的运用和优化措施。5.3测试与性能分析对助眠小程序进行全面的测试,包括功能测试、性能测试等,并分析测试结果。第6章结论与展望总结论文的研究成果,展望未来的研究方向和应用前景。6.1研究成果总结概括性地总结论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值