XRecyclerView+MVP+全选全不选+局部选择+计算总价+刷新

ShowOkHttpUtils
public class ShopOkHttpUtils {
private Handler handler=new Handler();
private static ShopOkHttpUtils mInstance;
private OkHttpClient okHttpClient;

//私有构造
private ShopOkHttpUtils(){
    //日志拦截
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    okHttpClient = new OkHttpClient.Builder()
            //日志拦截
            .addInterceptor(interceptor)
            //读
            .readTimeout(5,TimeUnit.SECONDS)
            //写
            .writeTimeout(5,TimeUnit.SECONDS)
            //连接超时
            .connectTimeout(5,TimeUnit.SECONDS)
            .build();


}

//单例模式
public static ShopOkHttpUtils getmInstance() {
    if (mInstance==null){
        synchronized (ShopOkHttpUtils.class){
            if (mInstance==null){
                mInstance=new ShopOkHttpUtils();
            }
        }
    }
    return mInstance;
}

//post请求
public void doPost(HashMap<String,String> params,final OkHttpCallback okHttpCallback){
    //请求方法体
    FormBody.Builder formbody = new FormBody.Builder();
    for (Map.Entry<String,String> p:params.entrySet()){
        formbody.add(p.getKey(),p.getValue());
    }
    final RequestBody requestBody = formbody.build();
    Request request = new Request.Builder()
            .url(ProductApi.SHOPCART_URL)
            .post(requestBody)
            .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            if (okHttpCallback!=null){
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okHttpCallback.failure("网络异常了哟!");
                    }
                });
            }
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (requestBody!=null){
                if (response.code()==200){
                    final String resulr = response.body().string();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            okHttpCallback.success(resulr);
                        }
                    });
                }
            }
        }
    });
}

}

ShowOkHttpUtils接口

public interface OkHttpCallback {
void success(String result);
void failure(String msg);
}

ShopCartContract契约类
public interface ShopCartContract {
public abstract class ShopCartPresenter{
public abstract void getShopCart(HashMap<String,String> params);
}

interface IShopCartModel{
    void getShopCart(HashMap<String,String> params, ICartModelCallback iCartModelCallback);
}
interface IShopCartView{
    void success(List<ShopCartBean.Cart> list);
    void failure(String msg);
}

}

ShopCartModel
public class ShopCartModel implements ShopCartContract.IShopCartModel {
private Handler handler=new Handler();
@Override
public void getShopCart(HashMap<String, String> params, final ICartModelCallback callback) {
ShopOkHttpUtils.getmInstance().doPost(params, new OkHttpCallback() {
@Override
public void success(final String result) {
handler.post(new Runnable() {
@Override
public void run() {
callback.success(result);
}
});
}

        @Override
        public void failure(final String msg) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callback.failure(msg);
                }
            });
        }
    });
}

}

IShopCartCallback接口
public interface ICartModelCallback {
void success(String result);
void failure(String msg);
}

ShopCartPresenter
public class ShopCartPresenter extends ShopCartContract.ShopCartPresenter {
private ShopCartModel shopCartModel;
private ShopCartContract.IShopCartView iShopCartView;
//iShopCartView的有参构造
public ShopCartPresenter(ShopCartContract.IShopCartView iShopCartView) {
shopCartModel = new ShopCartModel();
this.iShopCartView = iShopCartView;
}

@Override
public void getShopCart(HashMap<String, String> params) {
    shopCartModel.getShopCart(params, new ICartModelCallback() {
        //成功
        @Override
        public void success(String result) {
                //gson解析
                ShopCartBean shopCartBean = new Gson().fromJson(result, ShopCartBean.class);
                iShopCartView.success(shopCartBean.data);
        }
        //失败
        @Override
        public void failure(String msg) {
            iShopCartView.failure(msg);
        }
    });
}

}

ShopCartAdapter 一级适配器
public class ShopCartAdapter extends XRecyclerView.Adapter<ShopCartAdapter.MyVh> implements ShopCartCallback {
private Context context;
private List<ShopCartBean.Cart> carts;
private ShopCartUICallnack shopCartUICallnack;

public void setShopCartUICallnack(ShopCartUICallnack shopCartUICallnack) {
    this.shopCartUICallnack = shopCartUICallnack;
}

public void addData(List<ShopCartBean.Cart> list) {
    if (list!=null&&carts!=null){
        carts.addAll(list);
        notifyDataSetChanged();
    }
    this.carts = carts;
}

public ShopCartAdapter(Context context, List<ShopCartBean.Cart> carts) {
    this.context = context;
    this.carts = carts;
}

@NonNull
@Override
public ShopCartAdapter.MyVh onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view=LayoutInflater.from(context).inflate(R.layout.cart_item_layout,viewGroup,false);
    return new MyVh(view);
}

@Override
public void onBindViewHolder(@NonNull final ShopCartAdapter.MyVh myVh, int i) {
    for (ShopCartBean.Cart.Product product : carts.get(i).list) {
        product.pos=i;
    }
    final ShopCartBean.Cart cart = carts.get(i);
    myVh.title.setText(cart.sellerName);
    myVh.checkbox.setChecked(cart.isCheckbox);
    ShopProductAdapter shopProductAdapter = new ShopProductAdapter(context, cart.list);
    //接口监听回调
    shopProductAdapter.setShopCartCallback(this);
    myVh.rv.setLayoutManager(new LinearLayoutManager(context));
    myVh.rv.setAdapter(shopProductAdapter);

    myVh.checkbox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            cart.isCheckbox=myVh.checkbox.isChecked();
            for (ShopCartBean.Cart.Product product : cart.list) {
                product.isProductCheckbox=cart.isCheckbox;
            }
            notifyDataSetChanged();
            if (shopCartUICallnack!=null){
                shopCartUICallnack.notifyCart();
            }
        }
    });
}

@Override
public int getItemCount() {
    return carts==null?0:carts.size();
}

/**
 * 二级列表选中状态的监听,通知一级列表刷新数据
 * @param isChecked
 * @param position
 */
@Override
public void notifyCartItem(boolean isChecked, int position) {
    //设置一级列表的选中状态
    carts.get(position).isCheckbox=isChecked;
    notifyDataSetChanged();

}
/**
 * 数据改变后,通知首页价格联动
 */
@Override
public void notifyNum() {
    if (shopCartUICallnack!=null){
        shopCartUICallnack.notifyCart();
    }
}

public class MyVh extends RecyclerView.ViewHolder {

    private CheckBox checkbox;
    private TextView title;
    private XRecyclerView rv;

    public MyVh(@NonNull View itemView) {
        super(itemView);
        checkbox = itemView.findViewById(R.id.checkbox);
        title = itemView.findViewById(R.id.title);
        rv = itemView.findViewById(R.id.rv);
    }
}

}

ShopProductAdapter二级适配器
public class ShopProductAdapter extends XRecyclerView.Adapter<ShopProductAdapter.MyVh> {
private Context context;
private List<ShopCartBean.Cart.Product> products;
private ShopCartCallback shopCartCallback;

public void setShopCartCallback(ShopCartCallback shopCartCallback) {
    this.shopCartCallback = shopCartCallback;
}

public ShopProductAdapter(Context context, List<ShopCartBean.Cart.Product> products) {
    this.context = context;
    this.products = products;
}

@NonNull
@Override
public ShopProductAdapter.MyVh onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view=LayoutInflater.from(context).inflate(R.layout.product_item_layout,viewGroup,false);
    return new MyVh(view);
}

@Override
public void onBindViewHolder(@NonNull final ShopProductAdapter.MyVh myVh, final int i) {
    final ShopCartBean.Cart.Product product = products.get(i);
    myVh.checkbox.setChecked(product.isProductCheckbox);
    String[] img = product.images.split("\\|");
    if (img!=null&&img.length>0){
        Glide.with(context).load(img[0]).into(myVh.image);
    }
    myVh.price.setText("¥:"+product.price);
    myVh.title.setText(product.title);
    myVh.checkbox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            product.isProductCheckbox=myVh.checkbox.isChecked();
            shopCartCallback.notifyNum();
            for (ShopCartBean.Cart.Product product1 : products) {
                if (!product1.isProductCheckbox){
                    if (shopCartCallback!=null){
                        shopCartCallback.notifyCartItem(false,product.pos);
                    }
                    return;
                }
                shopCartCallback.notifyCartItem(true,product.pos);
            }
        }
    });
    myVh.addMinusView.setAddMinusCallback(new AddMinusView.AddMinusCallback() {
        @Override
        public void numCallback(int num) {
            product.productNum=num;//对当前商品的数量进行动态改变
            shopCartCallback.notifyNum();

        }
    });
}

@Override
public int getItemCount() {
    return products==null?0:products.size();
}

public class MyVh extends RecyclerView.ViewHolder {

    private CheckBox checkbox;
    private ImageView image;
    private TextView price;
    private TextView title;
    private AddMinusView addMinusView;

    public MyVh(@NonNull View itemView) {
        super(itemView);
        checkbox = itemView.findViewById(R.id.checkbox);
        image = itemView.findViewById(R.id.image);
        title = itemView.findViewById(R.id.title);
        price = itemView.findViewById(R.id.price);
        addMinusView = itemView.findViewById(R.id.addMinusView);
    }
}

}

FragmentFour
public class FragmentFour extends Fragment implements ShopCartContract.IShopCartView,XRecyclerView.LoadingListener,ShopCartUICallnack {
private XRecyclerView rv;
private CheckBox checkbox;
private ShopCartPresenter shopCartPresenter;
private ShopCartAdapter shopCartAdapter;
private List<ShopCartBean.Cart> carts;
private int page=1;
private HashMap<String, String> map;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragmentfour, container, false);
    //视图
    initView(view);
    initData();
    return view;
}
//数据
private void initData() {
    shopCartPresenter = new ShopCartPresenter(this);
    shopCartPresenter.getShopCart(new HashMap<String, String>());
    carts = new ArrayList<>();
    requestData();
}
//刷新加载
private void requestData() {
    map = new HashMap<>();
    map.put("uid","71");
    map.put("page",page+"");
    shopCartPresenter.getShopCart(map);

}

@Override
public void success(List<ShopCartBean.Cart> list) {
    if (list!=null){
        carts=list;
        for (ShopCartBean.Cart cart : carts) {
            for (ShopCartBean.Cart.Product product : cart.list) {
                product.productNum=1;
            }
        }
    }
    if (page==1){
        rv.refreshComplete();//加载完成,隐藏头尾加载进度布局
        shopCartAdapter = new ShopCartAdapter(getActivity(), list);
        shopCartAdapter.setShopCartUICallnack(this);
        rv.setAdapter(shopCartAdapter);
    }else{//下拉
        if (shopCartAdapter==null){
            shopCartAdapter = new ShopCartAdapter(getActivity(), list);
            rv.setAdapter(shopCartAdapter);
        }else{
            shopCartAdapter.addData(list);
        }
        rv.loadMoreComplete();
    }
}
//失败
@Override
public void failure(String msg) {

}
//视图
private void initView(View view) {
    rv = (XRecyclerView) view.findViewById(R.id.rv);
    checkbox = (CheckBox) view.findViewById(R.id.checkbox);
    rv.setLayoutManager(new LinearLayoutManager(getActivity()));
    rv.setLoadingListener(this);
    rv.setLoadingMoreEnabled(true);
    //全选全不选
    checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                for (ShopCartBean.Cart cart : carts) {
                    cart.isCheckbox=true;
                    for (ShopCartBean.Cart.Product product : cart.list) {
                        product.isProductCheckbox=true;
                    }
                }
            }else{
                for (ShopCartBean.Cart cart : carts) {
                    cart.isCheckbox=false;
                    for (ShopCartBean.Cart.Product product : cart.list) {
                        product.isProductCheckbox=false;
                    }
                }
            }
            //刷新
            shopCartAdapter.notifyDataSetChanged();
            getToTalprice();
        }
    });
}

//计算总价
private void getToTalprice() {
    double totalprice=0;
    for (ShopCartBean.Cart cart : carts) {
        for (ShopCartBean.Cart.Product product : cart.list) {
            if (product.isProductCheckbox){
                totalprice+=product.price*product.productNum;
            }
        }
        checkbox.setText("¥:"+totalprice);
    }

}

//下拉
@Override
public void onRefresh() {
    page=1;
    requestData();
}
//上拉
@Override
public void onLoadMore() {
    page++;
    requestData();
}

@Override
public void notifyCart() {
    getToTalprice();
}

}

CartApi
public class ShopCartApi {
public static final String SHOPCART_URL=“http://www.zhaoapi.cn/”;
}
ProductApi
public class ProductApi {
public static final String SHOPCART_URL=ShowApi.SHOW_UEL+“product/getCarts”;
}

ShopCartBean
public class ShopCartBean {
public String msg;
public String code;
public List data;
public class Cart{
public boolean isCheckbox;//一级列表是否被选中
public String sellerName;
public String sellerid;
public List list;
public class Product{
public boolean isProductCheckbox;//二级列表是否被选中
public String title;
public String images;
public double price;
public String pid;
public int pos;
public int productNum=1;
}
}
}

接口Callback
ShopCartCallback
public interface ShopCartCallback {
void notifyCartItem(boolean isChecked,int position);
void notifyNum();
}
ShopCartUICallnack
public interface ShopCartUICallnack {
void notifyCart();
}

自定义View AddMinusView加减
public class AddMinusView extends LinearLayout {

private TextView add;
private EditText ed_num;
private TextView minus;
private int num=1;

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

public AddMinusView(Context context,AttributeSet attrs) {
    this(context, attrs,0);
}

public AddMinusView(Context context,AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initData(context);
}

private void initData(Context context) {
    LayoutInflater.from(context).inflate(R.layout.add_minus_layout,this,true);
    add = findViewById(R.id.add);
    ed_num = findViewById(R.id.ed_num);
    minus = findViewById(R.id.minus);
    ed_num.setText("1");
    //添加
    add.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            num=Integer.parseInt(ed_num.getText().toString());
            num++;
            ed_num.setText(num+"");
            if (addMinusCallback!=null){
                addMinusCallback.numCallback(num);
            }
            addMinusCallback.numCallback(num);
        }
    });
    //减少
    minus.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            num=Integer.parseInt(ed_num.getText().toString());
            num--;
            if (num==0){
                num=1;
                Toast.makeText(getContext(),"不能再减了",Toast.LENGTH_SHORT).show();
                return;
            }
            ed_num.setText(num+"");
            if (addMinusCallback!=null){
                addMinusCallback.numCallback(num);
            }
            addMinusCallback.numCallback(num);
        }
    });

}
private AddMinusCallback addMinusCallback;

public void setAddMinusCallback(AddMinusCallback addMinusCallback) {
    this.addMinusCallback = addMinusCallback;
}
public interface AddMinusCallback{
    void numCallback(int num);
}

}

FragmentFour主布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="8dp"
    app:cardElevation="5dp"
    app:cardBackgroundColor="#ffffff"
    android:background="#006fff">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <com.jcodecraeer.xrecyclerview.XRecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp">
            <CheckBox
                android:id="@+id/checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="¥:0.0"
                android:layout_centerVertical="true"/>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="去结算"
                android:textColor="#ffffff"
                android:background="@drawable/shapee"
                android:layout_alignParentRight="true"
                />
        </RelativeLayout>
    </LinearLayout>


</android.support.v7.widget.CardView>

cart_item_layout一级布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="10dp"
    app:cardElevation="5dp"
    android:padding="10dp"
    android:layout_margin="10dp"
    app:cardBackgroundColor="#ffffff">

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

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

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

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="商品名称" />
        </LinearLayout>

        <com.jcodecraeer.xrecyclerview.XRecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</android.support.v7.widget.CardView>

product_item_layout子布局

<?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">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/left_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true">
            <CheckBox
                android:id="@+id/checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"/>
            <ImageView
                android:id="@+id/image"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:layout_gravity="center"
                android:src="@mipmap/ic_launcher"/>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                <TextView
                    android:id="@+id/title"
                    android:layout_width="230dp"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:ellipsize="end"
                    android:lines="2"
                    android:text="商品标题"/>
                <TextView
                    android:id="@+id/price"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:text="价格"
                    android:lines="2"
                    android:ellipsize="end"
                    android:textColor="#ff00"
                    android:textSize="14sp"/>
            </LinearLayout>
        </LinearLayout>
        <com.example.simulationexam.widget.AddMinusView
            android:id="@+id/addMinusView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>
</LinearLayout>

**计算器布局**

<?xml version="1.0" encoding="utf-8"?>








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值