購物車模組詳細程式碼
//先是佈局主頁面
<?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="match_parent">
<!--標題欄--> <RelativeLayout android:id="@+id/rl_title" android:layout_width="match_parent" android:layout_height="48dp">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="購物車" />
<TextView android:id="@+id/txt_edit_or_finish" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:padding="5dp" android:text="編輯" />
</RelativeLayout>
<!--底部結算--> <RelativeLayout android:id="@+id/rl_bottom" android:layout_width="match_parent" android:layout_height="48dp" android:layout_alignParentBottom="true">
<CheckBox android:id="@+id/cb_total_select" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:text="全選" />
<TextView android:id="@+id/txt_total_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:layout_toRightOf="@id/cb_total_select" android:textColor="#c23636" />
<Button android:id="@+id/btn_calu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:text="結算" /> </RelativeLayout>
<android.support.v7.widget.RecyclerView android:id="@+id/rv_shopper" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/rl_bottom" android:layout_below="@id/rl_title"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
//商品佈局
<?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:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:orientation="horizontal" android:padding="5dp">
<CheckBox android:id="@+id/cb_shopper" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@null" />
<TextView android:id="@+id/txt_shopper_name" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
<android.support.v7.widget.RecyclerView android:id="@+id/rv_product" android:layout_width="match_parent" android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</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="wrap_content" android:orientation="horizontal" android:paddingBottom="5dp" android:paddingLeft="20dp" android:paddingRight="5dp" android:paddingTop="5dp">
<CheckBox android:id="@+id/cb_product" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@null" />
<ImageView android:id="@+id/img_product" android:layout_width="45dp" android:layout_height="45dp" android:layout_marginLeft="10dp" android:layout_toRightOf="@id/cb_product" />
<com.bwie.cart1023.widget.AddDecreaseView android:id="@+id/adv_product" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true"></com.bwie.cart1023.widget.AddDecreaseView>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toLeftOf="@id/adv_product" android:layout_toRightOf="@id/img_product" android:orientation="vertical">
<TextView android:id="@+id/txt_product_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" />
<TextView android:id="@+id/txt_single_price" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
</RelativeLayout>
//加減器的佈局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="70dp" android:layout_height="wrap_content">
<TextView android:id="@+id/txt_decrease" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e78b8b" android:padding="5dp" android:text=" - " />
<TextView android:id="@+id/txt_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:background="#e78b8b" android:padding="5dp" android:text=" + " />
<TextView android:id="@+id/txt_num" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toLeftOf="@id/txt_add" android:layout_toRightOf="@id/txt_decrease" android:gravity="center" android:maxLength="3" /> </RelativeLayout>
//Inter層
package com.bwie.cart1023.inter;
/** * Created by eric on 2018/10/22. */
public interface INetCallBack { void success(Object obj);
void failed(Exception e); }
//Utils層
package com.bwie.cart1023.utils;
import android.os.Handler; import android.os.Looper;
import com.bwie.cart1023.inter.INetCallBack; import com.google.gson.Gson;
import java.io.IOException; import java.lang.reflect.Type; import java.util.concurrent.TimeUnit;
import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor;
/** * Created by eric on 2018/10/22. */
public class HttpUtils { private static volatile HttpUtils instance;
private OkHttpClient client;
private Handler handler = new Handler(Looper.getMainLooper());
private HttpUtils() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .addInterceptor(interceptor) .build(); }
public static HttpUtils getInstance() { if (instance == null) { synchronized (HttpUtils.class) { if (null == instance) { instance = new HttpUtils(); } } } return instance; }
public void get(String url, final INetCallBack callBack, final Type type) { Request request = new Request.Builder() .get() .url(url) .build();
Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { callBack.failed(e); } }); }
@Override public void onResponse(Call call, Response response) throws IOException { String result = response.body().string(); Gson gson = new Gson(); final Object o = gson.fromJson(result, type); handler.post(new Runnable() { @Override public void run() { callBack.success(o); } }); } }); } }
//Utils轉換層
package com.bwie.cart1023.utils;
/** * Created by eric on 2018/10/22. */
public class StringUtils { public static String https2Http(String url) { return url.replace("https", "http"); } }
//bean層
package com.bwie.cart1023.bean;
import java.util.List;
/** * Created by eric on 2018/10/23. */
public class MessageBean<T> { private String msg; private String code; private T 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 T getData() { return data; }
public void setData(T data) { this.data = data; } }
//網路請求層省略
//第三層
package com.bwie.cart1023.bean;
/** * Created by eric on 2018/10/23. */
public class Shopper<T> { private String sellerid; private String sellerName; private boolean isChecked; private T list;
public String getSellerid() { return sellerid; }
public void setSellerid(String sellerid) { this.sellerid = sellerid; }
public String getSellerName() { return sellerName; }
public void setSellerName(String sellerName) { this.sellerName = sellerName; }
public boolean isChecked() { return isChecked; }
public void setChecked(boolean checked) { isChecked = checked; }
public T getList() { return list; }
public void setList(T list) { this.list = list; } }
//M層
package com.bwie.cart1023.cart.model;
import com.bwie.cart1023.inter.INetCallBack; import com.bwie.cart1023.utils.HttpUtils;
import java.lang.reflect.Type;
/** * Created by eric on 2018/10/23. */
public class CartModel { public void getData(String url, INetCallBack callBack, Type type) { HttpUtils.getInstance().get(url, callBack, type); } }
//V層
package com.bwie.cart1023.cart.view;
import com.bwie.cart1023.bean.MessageBean; import com.bwie.cart1023.bean.Product; import com.bwie.cart1023.bean.Shopper;
import java.util.List;
/** * Created by eric on 2018/10/23. */
public interface IView { void success(MessageBean<List<Shopper<List<Product>>>> data);
void failed(Exception e); }
//P層
package com.bwie.cart1023.cart.presenter;
import com.bwie.cart1023.bean.MessageBean; import com.bwie.cart1023.bean.Product; import com.bwie.cart1023.bean.Shopper; import com.bwie.cart1023.cart.model.CartModel; import com.bwie.cart1023.cart.view.IView; import com.bwie.cart1023.inter.INetCallBack; import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type; import java.util.List;
/** * Created by eric on 2018/10/23. */
public class CartPresenter { private IView iv; private CartModel model;
public void attach(IView iv) { this.iv = iv; model = new CartModel(); }
public void getData() { String url = "http://www.zhaoapi.cn/product/getCarts?uid=1538"; Type type = new TypeToken<MessageBean<List<Shopper<List<Product>>>>>() { }.getType();
model.getData(url, new INetCallBack() { @Override public void success(Object obj) { MessageBean<List<Shopper<List<Product>>>> data = (MessageBean<List<Shopper<List<Product>>>>) obj; iv.success(data); }
@Override public void failed(Exception e) { iv.failed(e); } }, type);
}
public void detach() { if (iv != null) { iv = null; } } }
//加減器
package com.bwie.cart1023.widget;
import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView;
import com.bwie.cart1023.R;
/** * Created by eric on 2018/10/23. */
public class AddDecreaseView extends RelativeLayout implements View.OnClickListener { private TextView txtAdd; private TextView txtDecrease; private TextView txtNum;
private int num;
public interface OnAddDecreaseClickListener { void add(int num);
void decrease(int num); }
private OnAddDecreaseClickListener listener;
public void setOnAddDecreaseClickListener(OnAddDecreaseClickListener listener) { this.listener = listener; }
public AddDecreaseView(Context context) { this(context, null); }
public AddDecreaseView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public AddDecreaseView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); }
private void init(Context context) { View.inflate(context, R.layout.item_add_decrease, this); txtAdd = findViewById(R.id.txt_add); txtDecrease = findViewById(R.id.txt_decrease); txtNum = findViewById(R.id.txt_num);
txtNum.setText("1");
txtAdd.setOnClickListener(this); txtDecrease.setOnClickListener(this);
}
public void setNum(int num) { this.num = num; txtNum.setText(num + ""); }
public int getNum() { return num; }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.txt_add: num++; txtNum.setText(num + ""); if (listener != null) { listener.add(num); } break; case R.id.txt_decrease: if (num > 1) { num--; } txtNum.setText(num + ""); if (listener != null) { listener.decrease(num); } break; } } }
//兩個Adapter
package com.bwie.cart1023.adapter;
import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView;
import com.bumptech.glide.Glide; import com.bwie.cart1023.R; import com.bwie.cart1023.bean.Product; import com.bwie.cart1023.utils.StringUtils; import com.bwie.cart1023.widget.AddDecreaseView;
import java.util.List;
/** * Created by eric on 2018/10/23. */
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> { private Context context; private List<Product> list;
// 二級條目(商品)點選監聽 public interface OnProductClickListener { void onProductClick(int position, boolean isChecked); }
private OnProductClickListener productClickListener;
public void setOnProductClickListener(OnProductClickListener listener) { this.productClickListener = listener; }
// 加減器發生變化的監聽 public interface OnAddDecreaseProductListener { void onChange(int position, int num); }
private OnAddDecreaseProductListener productListener;
public void setOnAddDecreaseProductListener(OnAddDecreaseProductListener listener) { this.productListener = listener; }
public ProductAdapter(Context context, List<Product> list) { this.context = context; this.list = list; }
@NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = View.inflate(context, R.layout.item_product, null); ViewHolder holder = new ViewHolder(v); return holder; }
@Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { final Product product = list.get(position); String images = product.getImages(); // 商品圖片 if (!TextUtils.isEmpty(images)) { String[] strings = images.split("\\|"); if (strings.length > 0) { Glide.with(context) .load(StringUtils.https2Http(strings[0])) .into(holder.imgProduct); } }
holder.txtProductName.setText(product.getTitle()); holder.txtSinglePriice.setText(String.valueOf(product.getPrice()));
holder.advProduct.setNum(product.getNum()); // 加減器新增點選事件 holder.advProduct.setOnAddDecreaseClickListener(new AddDecreaseView.OnAddDecreaseClickListener() { @Override public void add(int num) { product.setNum(num);
if (productListener != null) { productListener.onChange(position, num); } }
@Override public void decrease(int num) { product.setNum(num); if (productListener != null) { productListener.onChange(position, num); } } });
// 商品的複選框 holder.cbProduct.setOnCheckedChangeListener(null); holder.cbProduct.setChecked(product.isChecked()); holder.cbProduct.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { product.setChecked(isChecked); if (productClickListener != null) { productClickListener.onProductClick(position, isChecked); } } });
}
@Override public int getItemCount() { return list.size(); }
class ViewHolder extends RecyclerView.ViewHolder { private CheckBox cbProduct; private ImageView imgProduct; private TextView txtProductName; private TextView txtSinglePriice; private AddDecreaseView advProduct;
public ViewHolder(View itemView) { super(itemView); cbProduct = itemView.findViewById(R.id.cb_product); imgProduct = itemView.findViewById(R.id.img_product); txtSinglePriice = itemView.findViewById(R.id.txt_single_price); advProduct = itemView.findViewById(R.id.adv_product); txtProductName = itemView.findViewById(R.id.txt_product_name); } } }
//另一個Adapter
package com.bwie.cart1023.adapter;
import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView;
import com.bwie.cart1023.R; import com.bwie.cart1023.bean.Product; import com.bwie.cart1023.bean.Shopper;
import java.util.List;
/** * Created by eric on 2018/10/23. */
public class ShopperAdapter extends RecyclerView.Adapter<ShopperAdapter.ViewHolder> { private Context context; private List<Shopper<List<Product>>> list;
public ShopperAdapter(Context context, List<Shopper<List<Product>>> list) { this.context = context; this.list = list; }
// 一級列表(商家)發生變化的介面 public interface OnShopperClickListener { void onShopperClick(int position, boolean isCheck); }
private OnShopperClickListener shopperClickListener;
public void setOnShopperClickListener(OnShopperClickListener listener) { this.shopperClickListener = listener; }
// 二級列表的加減器監聽 private ProductAdapter.OnAddDecreaseProductListener productListener;
public void setOnAddDecreaseProductListener(ProductAdapter.OnAddDecreaseProductListener listener) { this.productListener = listener; }
@NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = View.inflate(context, R.layout.item_shopper, null); ViewHolder holder = new ViewHolder(v); return holder; }
@Override public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) { final Shopper<List<Product>> shopper = list.get(position); holder.txtShopperName.setText(shopper.getSellerName());
// 產品的列表 RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(context); holder.rvProduct.setLayoutManager(pLayoutManager); final ProductAdapter adapter = new ProductAdapter(context, shopper.getList()); // 給二級列表新增一個加減器的監聽 if (productListener != null) { adapter.setOnAddDecreaseProductListener(productListener); } // 二級條目(商品)複選框點選事件 adapter.setOnProductClickListener(new ProductAdapter.OnProductClickListener() { @Override public void onProductClick(int position, boolean isChecked) { // 當前商品未選中,商家也就未選中 if (!isChecked) { shopper.setChecked(false); // 只要是當前條目未選中,全選複選框也就沒選中 shopperClickListener.onShopperClick(position, false); } else { // 當前商品如果選中,需要遍歷商家所有的商品是否選中 // 迴圈遍歷之前先設定一個true標誌位,只要有一條商品沒有被選中,商家也就選中,標誌位變成false boolean isAllProductSelected = true; for (Product product : shopper.getList()) { if (!product.isChecked()) { isAllProductSelected = false; break; } } shopper.setChecked(isAllProductSelected); // 當前商品選中時,需要迴圈遍歷所有的商家是否被選中來確認外部全選複選框的狀態 shopperClickListener.onShopperClick(position, true); } // 資料發生變化之後重新整理介面卡 notifyDataSetChanged(); productListener.onChange(0, 0); } });
holder.rvProduct.setAdapter(adapter);
// 先取消掉之前的點選變化監聽 holder.cbSHopper.setOnCheckedChangeListener(null);
// 設定好初始化的狀態 holder.cbSHopper.setChecked(shopper.isChecked());
// 等設定完初始化狀態之後再設定我們自己的監聽 // 商家列表中的複選框 holder.cbSHopper.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { shopper.setChecked(isChecked);
// 1.商家被選中的時候,子類所有的商品應該被選中 // if (isChecked) { List<Product> productList = shopper.getList(); for (Product product : productList) { product.setChecked(isChecked); } // 子類商品的介面卡重新整理 adapter.notifyDataSetChanged(); // } // 當點選一級條目的時候,外部的全選按鈕狀態發生變化 if (shopperClickListener != null) { shopperClickListener.onShopperClick(position, isChecked); } } }); }
@Override public int getItemCount() { return list.size(); }
class ViewHolder extends RecyclerView.ViewHolder { private CheckBox cbSHopper; private TextView txtShopperName; private RecyclerView rvProduct;
public ViewHolder(View itemView) { super(itemView); cbSHopper = itemView.findViewById(R.id.cb_shopper); txtShopperName = itemView.findViewById(R.id.txt_shopper_name); rvProduct = itemView.findViewById(R.id.rv_product); } } }