1. 程式人生 > >小Dome06:實現JD購物車功能

小Dome06:實現JD購物車功能

底層build.gradle

ext{
    retrofitVersion = '2.4.0'
    rxandroid = '2.1.0'
    butterknife = '8.8.1'
    okhttp = '3.11.0'
}

繼承base

本app的build.gradle

compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
    compile 'com.facebook.fresco:fresco:0.11.0'
    compile 'com.hjm:BottomTabBar:1.1.1'
    implementation 'com.sunfusheng:marqueeview:1.3.2'
    compile 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0-alpha-14'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    compile 'com.jcodecraeer:xrecyclerview:1.5.9'
    compile 'com.youth.banner:banner:1.4.9'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.gyf.immersionbar:immersionbar:2.3.1'
    compile "com.squareup.retrofit2:retrofit:$rootProject.ext.retrofitVersion"
    compile "com.squareup.retrofit2:converter-gson:$rootProject.ext.retrofitVersion"
    compile "com.squareup.retrofit2:adapter-rxjava2:$rootProject.ext.retrofitVersion"
    compile 'io.reactivex.rxjava2:rxandroid:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.11.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    testCompile 'junit:junit:4.12'
    compile project(':base')
}
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.0.1'
            }
        }
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

<application
    android:name=".app.App"

activity_main.xml

<com.hjm.bottomtabbar.BottomTabBar
    android:id="@+id/tab_var"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

activity_fragment1.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:gravity="center"
    android:background="#CCCCCC"
    >

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="8"
        android:gravity="center"
        android:text="購物車"
        android:textSize="25dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:gravity="center"
        android:text="編輯"
        android:textSize="18dp"/>

</LinearLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1px"
    android:background="#909090"/>

<android.support.v7.widget.RecyclerView
    android:id="@+id/carGV"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="8" />

<RelativeLayout
    android:id="@+id/cart_bottom_layout"
    android:padding="5dp"
    android:background="#CCCCCC"
    android:textColor="#C0C0C0"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">

    <CheckBox
        android:layout_centerVertical="true"
        android:id="@+id/allCheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/totalpriceTv"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/allCheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="總價:¥0.0"/>

    <Button
        android:id="@+id/buy"
        android:layout_alignParentRight="true"
        android:text="去結算"
        android:textSize="20dp"
        android:textColor="#fff"
        android:background="#F23030"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#CCCCCC"/>

three_yi.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="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <CheckBox
            android:id="@+id/sellerCheckbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/sellerNameTv"
            android:text="商家"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="#999999"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/productXRV"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="#999999"/>

</LinearLayout>

three_er.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="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">

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

            <CheckBox
                android:id="@+id/productCheckbox"
                android:layout_gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

            <ImageView
                android:src="@mipmap/ic_launcher"
                android:id="@+id/product_icon"
                android:layout_width="80dp"
                android:layout_height="80dp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_marginLeft="10dp"
            android:layout_width="match_parent"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/title"
                android:text="商品標題"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <RelativeLayout
                android:layout_marginTop="15dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/price"
                    android:layout_alignParentLeft="true"
                    android:text="優惠價:¥99.99"
                    android:textColor="@android:color/holo_red_light"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

             <com.bwie.yuekao.shopcart.activity.MyJIaJianView
                    android:id="@+id/jiajianqi"
                    android:layout_alignParentRight="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="#999999"/>

</LinearLayout>

three_jiajian.xml

<?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:layout_margin="5dp"
    android:orientation="horizontal"
    android:background="@drawable/jia_jian_bg">

    <TextView
        android:id="@+id/jian"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="-"
        android:textSize="25sp"
        android:padding="5dp"/>

    <View
        android:layout_width="1px"
        android:layout_height="match_parent"
        android:background="#999999"/>

    <EditText
        android:id="@+id/num"
        android:layout_weight="1"
        android:text="1"
        android:gravity="center"
        android:background="#00000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <View
        android:layout_width="1px"
        android:layout_height="match_parent"
        android:background="#999999"/>

    <TextView
        android:id="@+id/jia"
        android:textSize="25sp"
        android:padding="5dp"
        android:text="+"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

jia_jian_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="#ffffff"/>
    <size android:width="100dp" android:height="30dp"/>
    <stroke android:width="1px" android:color="#999999"/>

</shape>

MyJIaJianView

public class MyJIaJianView extends LinearLayout {

    private TextView jiaTv,jiantv;
    private EditText numEt;
    private int num = 1;
    public MyJIaJianView(Context context) {
        this(context,null);
    }

    public MyJIaJianView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyJIaJianView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }
    //初始化自定義的佈局
    private void init(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.three_jiajian,this,true);
        jiantv = view.findViewById(R.id.jian);
        jiaTv = view.findViewById(R.id.jia);
        numEt = view.findViewById(R.id.num);
        numEt.setText(num+"");
        jiaTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                num++;
                numEt.setText(num+"");
                if (jiaJianListener!=null){
                    jiaJianListener.getNum(num);
                }
            }
        });
        jiantv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                num--;
                if (num<=0){
                    Toast.makeText(getContext(), "數量不能小於1", Toast.LENGTH_SHORT).show();
                    num = 1;
                }
                numEt.setText(num+"");

                if (jiaJianListener!=null){
                    jiaJianListener.getNum(num);
                }
            }
        });
    }
    public void setNumEt(int n) {
        numEt.setText(n+"");
        num = Integer.parseInt(numEt.getText().toString());
    }
    private JiaJianListener jiaJianListener;

    public void setJiaJianListener(JiaJianListener jiaJianListener) {
        this.jiaJianListener = jiaJianListener;
    }
    public interface JiaJianListener{
        void getNum(int num);
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {

    private BottomTabBar tab_var;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //沉浸式狀態列
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //隱藏ActionBar
            ActionBar actionBar = getSupportActionBar();
            actionBar.hide();
        }
        tab_var = (BottomTabBar) findViewById(R.id.tab_var);
        initView();
    }

    private void initView() {
        ImmersionBar.with(this).init();
        tab_var.init(getSupportFragmentManager())
                .setImgSize(50,50)
                .setFontSize(15)
                .setChangeColor(Color.RED,Color.GRAY)
                .addTabItem("購物車",R.drawable.syn, Fragment1.class)
                .addTabItem("我的",R.drawable.myn, Fragment2.class);
    }
}

ThreeBean

App

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
    }
}

ThreeApi

public interface ThreeApi {
    @POST("product/getCarts")
    @FormUrlEncoded
    Observable<ThreeBean> shopping(@FieldMap HashMap<String, String> prams);
}

Contants

public class Contants {
    public static final String BASE_RELEASE_URL = "http://www.zhaoapi.cn/";
}

ThreeContract

public interface ThreeContract {
    //Presenter
    abstract class ThreePresenter extends BasePresenter<ThreeModel,ThreeView> {
        public abstract void shopping(HashMap<String,String> parms);

        @Override
        public ThreeModel getmModel() {
            return new com.bwie.yuekao.shopcart.model.ThreeModel();
        }
    }
    //model層介面
    interface ThreeModel extends IBaseModel {
        Observable<ThreeBean> shopping(HashMap<String, String> parms);
    }
    //view層介面
    interface ThreeView extends IBaseView {
        void success(ThreeBean threeBean);
        void fail(String msg);
    }
}

ThreeModel

public class ThreeModel implements ThreeContract.ThreeModel{

    @Override
    public Observable<ThreeBean> shopping(HashMap<String,String> parms) {
        return  RetrofitUtils.getInstance().createApi(Contants.BASE_RELEASE_URL, ThreeApi.class)
                .shopping(parms).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }
}

ThreePresenter

public class ThreePresenter extends ThreeContract.ThreePresenter{

    @Override
    public void shopping(HashMap<String,String> parms) {
        mModel.shopping(parms).subscribe(new Consumer<ThreeBean>() {
            @Override
            public void accept(ThreeBean threeBean) throws Exception {
                mView.success(threeBean);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                mView.fail("網路有問題 ,請稍候再試");
            }
        });
    }
}

ThreeYiAdapter

public class ThreeYiAdapter extends RecyclerView.Adapter<ThreeYiAdapter.ThreeYiViewHolder> {

    private Context context;
    private List<ThreeBean.DataBean> date;

    public ThreeYiAdapter(Context context,List<ThreeBean.DataBean> date){
        this.context = context;
        this.date = date;
    }

    @Override
    public ThreeYiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.three_yi,parent,false);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        return new ThreeYiViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ThreeYiViewHolder holder, int position) {
        final ThreeBean.DataBean bean = date.get(position);
        holder.sellerCheckbox.setChecked(bean.isSelected());
        for (int i = 0; i < bean.getList().size(); i++) {
            if (!bean.getList().get(i).isSelected()){
                holder.sellerCheckbox.setChecked(false);
            }else {
                holder.sellerCheckbox.setChecked(true);
            }
        }
        holder.productXRV.setLayoutManager(new LinearLayoutManager(context));
        holder.sellerNameTv.setText(date.get(position).getSellerName());
        ThreeErAdapter threeErAdapter = new ThreeErAdapter(context,bean.getList());
        holder.productXRV.setAdapter(threeErAdapter);
        holder.sellerCheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (holder.sellerCheckbox.isChecked()){
                    bean.setSelected(true);
                    for (int i = 0; i < bean.getList().size(); i++) {
                        bean.getList().get(i).setSelected(true);
                    }
                }else {
                    bean.setSelected(false);
                    for (int i = 0; i < bean.getList().size(); i++) {
                        bean.getList().get(i).setSelected(false);
                    }
                }
                notifyDataSetChanged();
            }
        });
    }

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

    public class ThreeYiViewHolder extends RecyclerView.ViewHolder{

        private CheckBox sellerCheckbox;
        private TextView sellerNameTv;
        private RecyclerView productXRV;

        public ThreeYiViewHolder(View itemView) {
            super(itemView);
            sellerCheckbox = itemView.findViewById(R.id.sellerCheckbox);
            sellerNameTv = itemView.findViewById(R.id.sellerNameTv);
            productXRV = itemView.findViewById(R.id.productXRV);

        }
    }

    public List<ThreeBean.DataBean> getDate() {
        return date;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void notify(String msg) {
        notifyDataSetChanged();
    }

}

ThreeErAdapter

public class ThreeErAdapter extends RecyclerView.Adapter<ThreeErAdapter.ThreeErViewHolder>{

    private Context context;
    private List<ThreeBean.DataBean.ListBean> listBeans;

    public ThreeErAdapter(Context context,List<ThreeBean.DataBean.ListBean> listBeans){
        this.context = context;
        this.listBeans = listBeans;
    }

    @Override
    public ThreeErViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.three_er, parent, false);
        return new ThreeErViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ThreeErViewHolder holder, int position) {
        final ThreeBean.DataBean.ListBean bean = listBeans.get(position);
        holder.productCheckbox.setChecked(listBeans.get(position).isSelected());
        holder.title.setText(listBeans.get(position).getTitle());
        holder.price.setText("優惠價:¥"+listBeans.get(position).getBargainPrice());
        String[] imgs = bean.getImages().split("\\|");
        Glide.with(context).load(imgs[0]).into(holder.product_icon);
        holder.jiajianqi.setNumEt(bean.getNum());
        holder.jiajianqi.setJiaJianListener(new MyJIaJianView.JiaJianListener() {
            @Override
            public void getNum(int num) {
                bean.setNum(num);
                EventBus.getDefault().post("");
            }
        });
        holder.jiajianqi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(holder.productCheckbox.isChecked()){
                    bean.setSelected(true);
                }else{
                    bean.setSelected(false);
                }
                EventBus.getDefault().post("");
            }
        });
    }

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

    public class ThreeErViewHolder extends RecyclerView.ViewHolder{

        private CheckBox productCheckbox;
        private ImageView product_icon;
        private TextView title;
        private TextView price;
        private MyJIaJianView jiajianqi;

        public ThreeErViewHolder(View itemView) {
            super(itemView);
            productCheckbox = itemView.findViewById(R.id.productCheckbox);
            product_icon = itemView.findViewById(R.id.product_icon);
            title = itemView.findViewById(R.id.title);
            price = itemView.findViewById(R.id.price);
            jiajianqi = itemView.findViewById(R.id.jiajianqi);
        }
    }
}

Fragment1

public class Fragment1 extends BaseMvpFragment<ThreeContract.ThreeModel,ThreeContract.ThreePresenter> implements ThreeContract.ThreeView {

    @BindView(R.id.carGV)
    RecyclerView carGV;
    @BindView(R.id.cart_bottom_layout)
    RelativeLayout cart_bottom_layout;
    @BindView(R.id.allCheckbox)
    CheckBox allCheckbox;
    @BindView(R.id.totalpriceTv)
    TextView totalpriceTv;
    @BindView(R.id.buy)
    Button buy;
    private List<ThreeBean.DataBean> dataBeans;
    private ThreeYiAdapter threeYiAdapter;

    @OnClick(R.id.buy)
    public void buy() {

    }

    @Override
    protected void initData() {
        super.initData();
        carGV.setLayoutManager(new LinearLayoutManager(getActivity()));
        HashMap<String,String> prams = new HashMap<>();
        prams.put("uid","71");

        presenter.shopping(prams);
        allCheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (allCheckbox.isChecked()){
                    for (int i = 0; i < dataBeans.size(); i++) {
                        dataBeans.get(i).setSelected(true);
                        for (int i1 = 0; i1 < dataBeans.get(i).getList().size(); i1++) {
                            dataBeans.get(i).getList().get(i1).setSelected(true);
                        }
                    }
                }else {
                    for (int i = 0; i < dataBeans.size(); i++) {
                        dataBeans.get(i).setSelected(false);
                        for (int i1 = 0; i1 < dataBeans.get(i).getList().size(); i1++) {
                            dataBeans.get(i).getList().get(i1).setSelected(false);
                        }
                    }
                }
                threeYiAdapter.notifyDataSetChanged();
                numm();
            }
        });
    }

    @Override
    public BasePresenter initPresenter() {
        return new ThreePresenter();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void success(ThreeBean threeBean) {
        // Log.i("threeBean",threeBean.toString());
        dataBeans = threeBean.getData();
        threeYiAdapter = new ThreeYiAdapter(getActivity(),dataBeans);
        carGV.setAdapter(threeYiAdapter);
    }

    @Override
    public void fail(String msg) {

    }

    @Override
    protected int bindLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.activity_fragment1;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void notify(String msg) {
        StringBuilder stringBuilder = new StringBuilder();
        if (threeYiAdapter != null){
            for (int i = 0; i < threeYiAdapter.getDate().size(); i++) {
                stringBuilder.append(threeYiAdapter.getDate().get(i).isSelected());
                for (int i1 = 0; i1 < threeYiAdapter.getDate().get(i).getList().size(); i1++) {
                    stringBuilder.append(threeYiAdapter.getDate().get(i).getList().get(i1).isSelected());
                }
            }
        }
        if (stringBuilder.toString().contains("false")) {
            allCheckbox.setChecked(false);
        } else {
            allCheckbox.setChecked(true);
        }
        threeYiAdapter.notifyDataSetChanged();
        numm();
    }
    private void numm() {
        double mymax = 0;
        for (int i = 0; i < threeYiAdapter.getDate().size(); i++) {
            for (int i1 = 0; i1 < threeYiAdapter.getDate().get(i).getList().size(); i1++) {
                if (threeYiAdapter.getDate().get(i).getList().get(i1).isSelected()) {
                    ThreeBean.DataBean.ListBean listBean = threeYiAdapter.getDate().get(i).getList().get(i1);
                    mymax += Double.parseDouble(String.valueOf(listBean.getBargainPrice()))*listBean.getNum();
                }
            }
            totalpriceTv.setText("總價:¥"+mymax);

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}

Fragment2

public class Fragment2 extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(),R.layout.activity_fragment2,null);
        return view;
    }
}