购物车Activity
package com.example.yuekaomoni01.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Orientati er;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.example.yuekaomoni01.R;
import com.example.yuekaomoni01.adaper.ShoppAdaper;
import com.example.yuekaomoni01.api.Apis;
import com.example.yuekaomoni01.bean.ShoppCarBean;
import com.example.yuekaomoni01.presenter.PresenterImpl;
import com.example.yuekaomoni01.view.Iview;
import java.util.HashMap;
import java.util.Map;
public class ShoppCarActivity extends AppCompatActivity implements Iview {
private PresenterImpl presenter;
private RecyclerView recyclerView;
private CheckBox query;
private TextView text_total;
private TextView text_shopp;
private ShoppAdaper adaper;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppcar);
presenter = new PresenterImpl(this);
initView();
}
private void initView() {
//获取资源id
recyclerView = findViewById(R.id.recycle_view);
query = findViewById(R.id.query);
text_total = findViewById(R.id.text_total);
text_shopp = findViewById(R.id.text_shopp);
//1为不选中
query.setTag(1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(Orientati er.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
//创建适配器
adaper = new ShoppAdaper(this);
recyclerView.setAdapter(adaper);
//调用适配器里的接口
adaper.setUpdateListener(new ShoppAdaper.UpdateListener() {
@Override
public void setTotal(String total, String num, boolean allCheck) {
//设置ui的改变
text_shopp.setText(\"共\"+num+\"件商品\");
text_total.setText(\"总价:¥\"+total+\"元\");
if(allCheck){
query.setTag(2);
}else{
query.setTag(1);
}
query.setChecked(allCheck);
}
});
//这里只做ui更改, 点击全选按钮,,调到adapter里面操作
query.set Listener(new View. Listener() {
@Override
public void (View v) {
//调用adapter里面的方法 ,,把当前quanxuan状态传递过去
int tag = (int) query.getTag();
if(tag == 1){
query.setTag(2);
}else{
query.setTag(1);
}
adaper.queryAll(query.isChecked());
}
});
//请求网址
Map<String,String> map = new HashMap<>();
map.put(\"uid\",\"23027\");
presenter.startRequest(Apis.URL_CAR_COUNT,map,ShoppCarBean.class);
}
@Override
public void requestData( o) {
if(o instanceof ShoppCarBean){
ShoppCarBean bean = (ShoppCarBean) o;
if(bean==null || !bean.isSuccess()){
Toast.makeText(ShoppCarActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
}else{
adaper.add(bean);
}
}
}
@Override
public void requestFail( o) {
if(o instanceof Exception){
Exception e = (Exception) o;
e.printStackTrace();
}
Toast.makeText(ShoppCarActivity.this,\"网络请求错误\",Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
presenter.onDetach();
}
}
适配器
package com.example.yuekaomoni01.adaper;
import android.content.Context;
import android.support.annotation.NonNull;
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.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.yuekaomoni01.R;
import com.example.yuekaomoni01.bean.ShoppCarBean;
import com.example.yuekaomoni01.custom.CarCuctomView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ShoppAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private List<ShoppCarBean.DataBean.ListBean> list;
//存放商家id和商家名称的map集合
private Map<String,String> map = new HashMap<>();
public ShoppAdaper(Context mContext) {
this.mContext = mContext;
}
/**
* 添加数据并更新显示
* */
public void add(ShoppCarBean shoppBean){
//传进来的是bean对象
if(list == null){
list = new ArrayList<>();
}
//第一层遍历商家和商品
for(ShoppCarBean.DataBean bean:shoppBean.getData()){
//把商品的id和商品的名称添加到map集合里 ,,为了之后方便调用
map.put(bean.getSellerid(),bean.getSellerName());
//第二层遍历里面的商品
for(int i = 0;i<bean.getList().size();i++){
//添加到list集合里
list.add(bean.getList().get(i));
}
}
//调用方法 设置显示或隐藏 商铺名
setFirst(list);
notifyDataSetChanged();
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.shopp_car_item1,viewGroup,false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int i) {
/**
* 设置商铺的 shop_checkbox和商铺的名字 显示或隐藏
* */
final MyViewHolder holder = (MyViewHolder) viewHolder;
if(list.get(i).getIsFirst() == 1){
//显示商家
holder.shop_check.setVisibility(View.VISIBLE);
holder.shopp_commodity.setVisibility(View.VISIBLE);
//设置选中状态
holder.shop_check.setChecked(list.get(i).isShop_check());
holder.shopp_commodity.setText(map.get(String.valueOf(list.get(i).getSellerid())));
}else{
//隐藏
holder.shop_check.setVisibility(View.GONE);
holder.shopp_commodity.setVisibility(View.GONE);
}
//拆分images字段
String[] str = list.get(i).getImages().split(\"\\\\|\");
//设置商品的图片
Glide.with(mContext).load(str[0]).into(holder.item_image);
//控制商品的checkbox,根据字段改变
holder.item_check.setChecked(list.get(i).isItem_check());
holder.item_name.setText(list.get(i).get ());
holder.item_price.setText(list.get(i).getPrice()+\"\");
//调用customview里的方法设置加减号中间的数字
holder.custom.setEditText(list.get(i).getNum());
//商铺的shop_checkbox点击事件 ,控制商品的item_checkbox
holder.shop_check.set Listener(new View. Listener() {
@Override
public void (View v) {
//先改变数据源中的shop_check
list.get(i).setShop_check(holder.shop_check.isChecked());
for(int a = 0;a<list.size();a++){
//如果是同一家商铺的 都给成相同状态
if(list.get(i).getSellerid() == list.get(a).getSellerid()){
//当前条目的选中状态 设置成 当前商铺的选中状态
list.get(a).setItem_check(holder.shop_check.isChecked());
}
}
//刷新适配器
notifyDataSetChanged();
//调用求和的方法
sum(list);
}
});
//商品的item_checkbox点击事件,控制商铺的shop_checkbox
holder.item_check.set Listener(new View. Listener() {
@Override
public void (View v) {
//先改变数据源中的item_checkbox
list.get(i).setItem_check(holder.item_check.isChecked());
//反向控制商铺的shop_checkbox
for(int s = 0;s<list.size();s++){
for(int j = 0;j<list.size();j++){
//如果两个商品是同一家店铺的 并且 这两个商品的item_checkbox选中状态不一样
if(list.get(s).getSellerid() == list.get(j).getSellerid()&&!list.get(j).isItem_check()){
//就把商铺的shop_checkbox改成false
list.get(s).setShop_check(false);
break;
}else{
//同一家商铺的商品 选中状态都一样,就把商铺shop_checkbox状态改成true
list.get(s).setShop_check(true);
}
}
}
//更新适配器
notifyDataSetChanged();
//调用求和的方法
sum(list);
}
});
//删除条目的点击事件
holder.item_del.set Listener(new View. Listener() {
@Override
public void (View v) {
//移除集合中的当前数据
list.remove(i);
//删除完当前的条目 重新判断商铺的显示隐藏
setFirst(list);
//调用重新求和
sum(list);
notifyDataSetChanged();
}
});
//加减号的监听,
holder.custom.setCustomCallBack(new CarCuctomView.CustomCallBack() {
@Override
public void callBack(int count) {
//改变数据源中的数量
list.get(i).setNum(count);
notifyDataSetChanged();
sum(list);
}
@Override
public void shuruzhi(int count) {
list.get(i).setNum(count);
notifyDataSetChanged();
sum(list);
}
});
}
/**
* 设置数据源,控制是否显示商家
* */
private void setFirst(List<ShoppCarBean.DataBean.ListBean> list) {
if(list.size()>0){
//如果是第一条数据就设置isFirst为1
list.get(0).setIsFirst(1);
//从第二条开始遍历
for(int i=1;i<list.size();i++){
//如果和前一个商品是同一家商店的
if(list.get(i).getSellerid() == list.get(i-1).getSellerid()){
//设置成2不显示商铺
list.get(i).setIsFirst(2);
}else{
//设置成1显示商铺
list.get(i).setIsFirst(1);
//如果当前条目选中,把当前的商铺也选中
if(list.get(i).isItem_check() == true){
list.get(i).setShop_check(list.get(i).isItem_check());
}
}
}
}
}
//求和的方法
private void sum(List<ShoppCarBean.DataBean.ListBean> list) {
//初始的总价为0
int totalNum = 0;
double totalPrice = 0.0;
boolean allCheck = true;
for(int i = 0;i<list.size();i++){
//把 已经选中的 条目 计算价格
if(list.get(i).isItem_check()){
totalNum += list.get(i).getNum();
totalPrice+= list.get(i).getNum()*list.get(i).getPrice();
}else{
//如果有个未选中,就标记为false
allCheck = false;
}
}
//接口回调出去 把总价 总数量 和allcheck 传给view层
updateListener.setTotal(totalPrice+\"\",totalNum+\"\",allCheck);
}
//view层调用这个方法, 点击quanxuan按钮的操作
public void queryAll(boolean checked){
for(int i = 0;i<list.size();i++){
list.get(i).setShop_check(checked);
list.get(i).setItem_check(checked);
}
notifyDataSetChanged();
sum(list);
}
@Override
public int getItemCount() {
return list==null?0:list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public final CheckBox shop_check;
public final TextView shopp_commodity;
public final CheckBox item_check;
public final ImageView item_image;
public final TextView item_name;
public final TextView item_price;
public final CarCuctomView custom;
public final ImageView item_del;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
shop_check = itemView.findViewById(R.id.shop_check);
shopp_commodity = itemView.findViewById(R.id.shopp_commodity);
item_check = itemView.findViewById(R.id.item_check);
item_image = itemView.findViewById(R.id.item_image);
item_name = itemView.findViewById(R.id.item_name);
item_price = itemView.findViewById(R.id.item_price);
custom = itemView.findViewById(R.id.custom);
item_del = itemView.findViewById(R.id.item_del);
}
}
private UpdateListener updateListener;
public void setUpdateListener(UpdateListener updateListener){
this.updateListener = updateListener;
}
//定义接口
public interface UpdateListener{
void setTotal(String total,String num,boolean allCheck);
}
}
适配器的
<? version=\"1.0\" encoding=\"utf-8\"?>
<LinearLayout
ns:android=\"http://schemas.android.com/apk/res/android\"
android:layout_width=\"match_parent\"
android:layout_height=\"wrap_content\"
android:orientation=\"vertical\"
android:padding=\"15dp\"
>
<LinearLayout
android:layout_width=\"match_parent\"
android:layout_height=\"wrap_content\"
android:orientation=\"horizontal\"
>
<CheckBox
android:id=\"@+id/shop_check\"
android:layout_width=\"50dp\"
android:layout_height=\"50dp\" />
<TextView
android:id=\"@+id/shopp_commodity\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\"
android:layout_marginLeft=\"20dp\"
android:text=\"shopp_commodity\"
android:textSize=\"24sp\"
/>
</LinearLayout>
<LinearLayout
android:layout_width=\"match_parent\"
android:layout_height=\"wrap_content\"
android:orientation=\"horizontal\"
android:gravity=\"center_vertical\"
>
<CheckBox
android:id=\"@+id/item_check\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\" />
<ImageView
android:id=\"@+id/item_image\"
android:layout_width=\"120dp\"
android:layout_height=\"120dp\"
android:src=\"@mipmap/ic_launcher\"
/>
<LinearLayout
android:layout_width=\"wrap_content\"
android:layout_height=\"match_parent\"
android:layout_marginLeft=\"10dp\"
android:orientation=\"vertical\"
android:layout_weight=\"1\"
>
<TextView
android:id=\"@+id/item_name\"
android:layout_width=\"wrap_content\"
android:layout_height=\"0dp\"
android:layout_weight=\"1\"
android:textSize=\"18sp\"
android:text=\"name\"
android:maxLines=\"2\"
/>
<TextView
android:id=\"@+id/item_price\"
android:layout_width=\"wrap_content\"
android:layout_height=\"0dp\"
android:layout_weight=\"1\"
android:textSize=\"18sp\"
android:text=\"price\"
android:textColor=\"#f00\"
/>
<com.example.yuekaomoni01.custom.CarCuctomView
android:id=\"@+id/custom\"
android:layout_width=\"wrap_content\"
android:layout_height=\"0dp\"
android:layout_weight=\"1\"
/>
</LinearLayout>
<ImageView
android:id=\"@+id/item_del\"
android:layout_width=\"30dp\"
android:layout_height=\"30dp\"
android:layout_marginRight=\"10dp\"
android:src=\"@drawable/ic_del_name\"
/>
</LinearLayout>
</LinearLayout>
Activity 的
<? version=\"1.0\" encoding=\"utf-8\"?>
<android.support.constraint.ConstraintLayout ns:android=\"http://schemas.android.com/apk/res/android\"
android:layout_width=\"match_parent\"
android:layout_height=\"match_parent\"
ns:app=\"http://schemas.android.com/apk/res-auto\">
<ImageView
android:id=\"@+id/car_image\"
android:layout_width=\"40dp\"
android:layout_height=\"40dp\"
app:layout_constraintLeft_toLeftOf=\"parent\"
app:layout_constraintTop_toTopOf=\"parent\"
android:src=\"@drawable/ic_left_name\"
/>
<TextView
android:id=\"@+id/car_text\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\"
app:layout_constraintLeft_toLeftOf=\"parent\"
app:layout_constraintRight_toRightOf=\"parent\"
app:layout_constraintTop_toTopOf=\"@id/car_image\"
app:layout_constraintBottom_toBottomOf=\"@id/car_image\"
android:textSize=\"20sp\"
android:textColor=\"#000\"
android:text=\"购物车\"
/>
<android.support.v7.widget.RecyclerView
android:id=\"@+id/recycle_view\"
android:layout_width=\"0dp\"
android:layout_height=\"0dp\"
app:layout_constraintLeft_toLeftOf=\"parent\"
app:layout_constraintRight_toRightOf=\"parent\"
app:layout_constraintTop_toBottomOf=\"@id/car_image\"
app:layout_constraintBottom_toTopOf=\"@id/text_jiesuan\"
/>
<CheckBox
android:id=\"@+id/query\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\"
app:layout_constraintLeft_toLeftOf=\"parent\"
app:layout_constraintTop_toBottomOf=\"@id/recycle_view\"
app:layout_constraintBottom_toBottomOf=\"parent\"
/>
<TextView
android:id=\"@+id/text_query\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\"
app:layout_constraintLeft_toRightOf=\"@id/query\"
app:layout_constraintBottom_toBottomOf=\"@id/query\"
app:layout_constraintTop_toTopOf=\"@id/query\"
android:textSize=\"20sp\"
android:text=\"全选/反选\"
/>
<TextView
android:id=\"@+id/text_total\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\"
app:layout_constraintTop_toBottomOf=\"@id/recycle_view\"
app:layout_constraintLeft_toRightOf=\"@id/text_query\"
android:layout_marginLeft=\"10dp\"
android:text=\"总价:¥0元\"
android:textColor=\"#f00\"
android:textSize=\"18sp\"
/>
<TextView
android:id=\"@+id/text_shopp\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\"
app:layout_constraintTop_toBottomOf=\"@id/text_total\"
app:layout_constraintLeft_toRightOf=\"@id/text_query\"
app:layout_constraintBottom_toBottomOf=\"parent\"
android:layout_marginLeft=\"10dp\"
android:text=\"共0件商品\"
android:textSize=\"18sp\"
/>
<TextView
android:id=\"@+id/text_jiesuan\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\"
app:layout_constraintTop_toBottomOf=\"@id/recycle_view\"
app:layout_constraintBottom_toBottomOf=\"parent\"
app:layout_constraintRight_toRightOf=\"parent\"
android:text=\"去结算\"
android:textSize=\"26sp\"
android:background=\"@drawable/button_shape\"
android:gravity=\"center\"
/>
</android.support.constraint.ConstraintLayout>
APIs
package com.example.yuekaomoni01.api;
public class Apis {
public static final String URL_SHOW=\"http://www.zhaoapi.cn/product/searchProducts\";
public static final String URL_CAR=\"http://www.zhaoapi.cn/product/addCart\";
public static final String URL_CAR_COUNT=\"http://www.zhaoapi.cn/product/getCarts\";
//?keywords=%E6%89%8B%E6%9C%BA&page=1&sort=0
}
OKHttp
package com.example.yuekaomoni01.util;
import android.os.Handler;
import android.os.Looper;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
public class OkHttpUtils {
private static OkHttpUtils intance;
private final OkHttpClient httpClient;
private Handler handler = new Handler(Looper.myLooper());
public OkHttpUtils() {
//日志拦截器
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient = new OkHttpClient.Builder()
.connectTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build();
}
public static OkHttpUtils getIntance() {
if(intance == null){
synchronized (OkHttpUtils.class){
intance = new OkHttpUtils();
}
}
return intance;
}
/**
* 异步get请求
* */
public void doGet(String url, String params, final Class clazz, final ICallBack iCallBack){
Request request = new Request.Builder()
.url(url)
.get()
.build();
Call call = httpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
iCallBack.faniled(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
String result = response.body().string();
Gson gson = new Gson();
final o = gson.fromJson(result, clazz);
handler.post(new Runnable() {
@Override
public void run() {
iCallBack.success(o);
}
});
}catch (Exception e){
iCallBack.faniled(e);
}
}
});
}
/**
* 异步post请求
* */
public void doPost(String url, Map<String,String> map, final Class clazz, final ICallBack iCallBack){
FormBody.Builder builder = new FormBody.Builder();
for(Map.Entry<String,String> entry:map.entrySet()){
builder.add(entry.getKey(),entry.getValue());
}
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = httpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
iCallBack.faniled(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
String result = response.body().string();
Gson gson = new Gson();
final o = gson.fromJson(result, clazz);
handler.post(new Runnable() {
@Override
public void run() {
iCallBack.success(o);
}
});
}catch (Exception e){
iCallBack.faniled(e);
}
}
});
}
}
继续阅读与本文标签相同的文章
上一篇 :
简单的Word问题,为什么有90%的人被困扰?
-
将阿里云产品整合成为高校课程实训的训练营产品的实践(四)
2026-05-18栏目: 教程
-
中间人攻击,HTTPS也可以被碾压
2026-05-18栏目: 教程
-
什么叫做IaC,与DevOps有什么关系?如何实现?
2026-05-18栏目: 教程
-
解读《运维知识体系》,直面自动化运维的“灵魂八问”
2026-05-18栏目: 教程
-
阿里99大促 | 模型识别背后的样本生成
2026-05-18栏目: 教程
