购物车2

流失布局布局

<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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bawei.gouwuche.activity.MainActivity">

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

        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <EditText
                android:id="@+id/edt"
                android:textColorHighlight="#ff44ff"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入搜索内容" />
        </FrameLayout>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:id="@+id/but"
            android:background="#808080"
            android:textSize="20dp"
            android:text="搜索" />

    </LinearLayout>

    <com.bawei.gouwuche.widget.CustomView
        android:id="@+id/afl_cotent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </com.bawei.gouwuche.widget.CustomView>

</LinearLayout>

主页面布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_height="match_parent"
    tools:context="com.bawei.gouwuche.activity.CartActivity">

    <com.jcodecraeer.xrecyclerview.XRecyclerView
        android:id="@+id/cartGV"
        android:layout_above="@+id/cart_bottom_layout"
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <RelativeLayout
        android:id="@+id/cart_bottom_layout"

        android:padding="5dp"
        android:background="@android:color/darker_gray"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <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:textColor="#ffffff"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/allCheckbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="总价:"/>

        <Button
            android:id="@+id/buy"
            android:onClick="buy"
            android:layout_alignParentRight="true"
            android:text="去结算"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </RelativeLayout>

</RelativeLayout>

内部布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">

    <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.bawei.gouwuche.widget.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>

外部布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">

    <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"/>

</LinearLayout>

加减布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_margin="5dp"
    android:layout_height="match_parent"
    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="10"
        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>

流失布局

public class MainActivity extends AppCompatActivity {

    private EditText edt;
    private Button but;
    private CustomView afl_cotent;
    private LayoutInflater layoutInflater;
    private TextView tvAttrTag;
    private List<String> list2 = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView() {
        edt =  findViewById(R.id.edt);
        but = findViewById(R.id.but);
        afl_cotent =findViewById(R.id.afl_cotent);
        layoutInflater = LayoutInflater.from(this);
        but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = edt.getText().toString();
                View item = layoutInflater.inflate(R.layout.sub_item, null);
                tvAttrTag =item.findViewById(R.id.tv_attr_tag);
                list2.add(s);
                for (int i = 0; i < list2.size(); i++) {
                    tvAttrTag.setText(list2.get(i));
                    tvAttrTag.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(MainActivity.this, CartActivity.class);
                            startActivity(intent);
                        }
                    });
                }
                afl_cotent.addView(item);
            }
        });
    }
}

主页面

public class CartActivity extends AppCompatActivity implements IcartView, CartAllCheckboxListener {


    private XRecyclerView xRecyclerView;
    private CartAdapter cartAdapter;
    private List<CartBean.DataBean> list;
    private CheckBox allCheckbox;
    private TextView totalPriceTv;
    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        initView();

        initData();
    }

    /**
     * 初始化view
     */
    private void initView() {

        list = new ArrayList<>();
        xRecyclerView = findViewById(R.id.cartGV);
        allCheckbox = findViewById(R.id.allCheckbox);
        //设置线性布局管理器,listview的列表样式
        xRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        totalPriceTv =  findViewById(R.id.totalpriceTv);

        xRecyclerView.setLoadingMoreEnabled(true);//支持加载更多

        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {//下拉刷新

                page = 1;
                loadData();//子线程
//                xRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {//加载更多
                page++;

                loadData();
//                xRecyclerView.loadMoreComplete();

            }
        });

        //设置点击事件
        allCheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (allCheckbox.isChecked()) {//
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).setSelected(true);
                            for (int i1 = 0; i1 < list.get(i).getList().size(); i1++) {
                                list.get(i).getList().get(i1).setSelected(true);
                            }
                        }

                    }

                } else {
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).setSelected(false);
                            for (int i1 = 0; i1 < list.get(i).getList().size(); i1++) {
                                list.get(i).getList().get(i1).setSelected(false);
                            }
                        }

                    }
//                    totalPrice = 0;
                }

                cartAdapter.notifyDataSetChanged();//全部刷新

                totalPrice();

            }
        });

    }

    /**
     * 初始化数据
     */
    private void initData() {
        loadData();
    }

    /**
     * 请求数据
     */
    private void loadData() {
        HashMap<String, String> params = new HashMap<>();
        params.put("uid", "71");
        params.put("page",page+"");

        CartPesenter cartPesenter = new CartPesenter(this);
        cartPesenter.getCarts(params,Constants.GETCARTS);
    }
    /**
     * 刷新购物车列表
     *
     * @param cartBean
     */
    @Override
    public void success(CartBean cartBean) {

        // TODO: 2018/8/21 展示列表数据

        if (cartBean != null && cartBean.getData() != null) {

            if (page==1){

                list = cartBean.getData();
                cartAdapter = new CartAdapter(this, list);

                xRecyclerView.setAdapter(cartAdapter);
                xRecyclerView.refreshComplete();//把下拉刷新的进度view隐藏掉
            }else {
                if (cartAdapter!=null){
                    cartAdapter.addPageData(cartBean.getData());
                }
                xRecyclerView.loadMoreComplete();//
            }
            cartAdapter.setCartAllCheckboxListener(this);

        }


    }

    /**
     * 失败提示
     *
     * @param msg
     */
    @Override
    public void failure(String msg) {

        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 去结算
     *
     * @param view
     */
    public void buy(View view) {

    }

    /**
     * 全选按钮是否选中的回调
     */
    @Override
    public void notifyAllCheckboxStatus() {

        StringBuilder stringBuilder = new StringBuilder();
        if (cartAdapter != null) {
            for (int i = 0; i < cartAdapter.getCartList().size(); i++) {

                stringBuilder.append(cartAdapter.getCartList().get(i).isSelected());

                for (int i1 = 0; i1 < cartAdapter.getCartList().get(i).getList().size(); i1++) {

                    stringBuilder.append(cartAdapter.getCartList().get(i).getList().get(i1).isSelected());

                }
            }
        }

        System.out.println("sb=====" + stringBuilder.toString());

        //truetruefalsetruefalse

        if (stringBuilder.toString().contains("false")) {
            allCheckbox.setChecked(false);
//            totalPrice = 0;
        } else {
            allCheckbox.setChecked(true);
        }

        totalPrice();//计算总价

    }


    /**
     * 计算总价
     */
    private void totalPrice() {

        double totalPrice = 0;

        for (int i = 0; i < cartAdapter.getCartList().size(); i++) {

            for (int i1 = 0; i1 < cartAdapter.getCartList().get(i).getList().size(); i1++) {

                //计算总价的关键代码块
                if (cartAdapter.getCartList().get(i).getList().get(i1).isSelected()) {
                    CartBean.DataBean.ListBean listBean = cartAdapter.getCartList().get(i).getList().get(i1);
                    totalPrice += listBean.getBargainPrice() * listBean.getTotalNum();
                }


            }
        }
        totalPriceTv.setText("总价:¥"+totalPrice);



    }
}

外层适配器

public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> implements CartCheckListener {

    private Context mContext;
    private List<CartBean.DataBean> cartList;
    private CartAllCheckboxListener allCheckboxListener;

    public CartAdapter(Context context, List<CartBean.DataBean> list) {
        mContext = context;
        cartList = list;

    }

    public void addPageData(List<CartBean.DataBean> list){
        if (cartList!=null){
            cartList.addAll(list);
            notifyDataSetChanged();
        }
    }

    //暴露给购物车页面进行回调
    public void setCartAllCheckboxListener(CartAllCheckboxListener cartAllCheckboxListener) {
        allCheckboxListener = cartAllCheckboxListener;
    }

    @NonNull
    @Override
    public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(mContext).inflate(R.layout.cart_item_layout, parent, false);
        CartViewHolder viewHolder = new CartViewHolder(itemView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final CartViewHolder holder, final int position) {

        final CartBean.DataBean bean = cartList.get(position);

        holder.nameTv.setText(bean.getSellerName());

        holder.checkBox.setChecked(bean.isSelected());//根据bean对象的ischecked属性,动态设置选中状态
//        System.out.println("ischecked:" + bean.isChecked());
//        holder.checkBox.setChecked(bean.isChecked());


        holder.productXRV.setLayoutManager(new LinearLayoutManager(mContext));
        final ProductAdapter productAdapter = new ProductAdapter(mContext, bean.getList());
        holder.productXRV.setAdapter(productAdapter);
        productAdapter.setCheckListener(this);

        for (int i = 0; i < bean.getList().size(); i++) {

            if (!bean.getList().get(i).isSelected()){
                holder.checkBox.setChecked(false);
                break;//跳出循环
            }else{
                holder.checkBox.setChecked(true);
            }



        }
        //设置商家的checkbox点击事件,逻辑:勾选则子列表全部勾选,取消则全部取消
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (holder.checkBox.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();

                if (allCheckboxListener!=null){
                    allCheckboxListener.notifyAllCheckboxStatus();
                }

            }
        });
    }


    /**
     * 暴露修改之后的最新的集合数据
     * @return
     */
    public List<CartBean.DataBean> getCartList() {
        return cartList;
    }

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

    /**
     * 刷新适配器的回调
     */
    @Override
    public void notifyParent() {

        notifyDataSetChanged();
        if (allCheckboxListener!=null){
            allCheckboxListener.notifyAllCheckboxStatus();
        }

    }


//    @Override
//    public void notifyParent() {
//        notifyDataSetChanged();
//    }

    public class CartViewHolder extends RecyclerView.ViewHolder {
        private CheckBox checkBox;
        private TextView nameTv;
        private RecyclerView productXRV;

        public CartViewHolder(View itemView) {
            super(itemView);
            checkBox =itemView.findViewById(R.id.sellerCheckbox);
            nameTv =  itemView.findViewById(R.id.sellerNameTv);
            productXRV =itemView.findViewById(R.id.productXRV);
        }
    }
}

内部适配器

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.CartViewHolder> {

    private Context mContext;
    private List<CartBean.DataBean.ListBean> listBeanList;
    private CartCheckListener checkListener;//接口回调引用
    private CartAllCheckboxListener cartAllCheckboxListener;

    public ProductAdapter(Context context, List<CartBean.DataBean.ListBean> list) {
        mContext = context;
        listBeanList = list;
    }

    /**
     * 暴露给调用者去进行回调:对checklisener进行初始化
     * @param checkListener
     */
    public void setCheckListener(CartCheckListener checkListener) {
        this.checkListener = checkListener;
    }

    public void setCartAllCheckboxListener(CartAllCheckboxListener cartAllCheckboxListener) {
        this.cartAllCheckboxListener = cartAllCheckboxListener;
    }


    @NonNull
    @Override
    public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(mContext).inflate(R.layout.product_item_layout, parent, false);
        CartViewHolder viewHolder = new CartViewHolder(itemView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final CartViewHolder holder, int position) {

        final CartBean.DataBean.ListBean bean = listBeanList.get(position);

        holder.priceTv.setText("优惠价:¥" + bean.getBargainPrice());
        holder.titleTv.setText(bean.getTitle());
        String[] imgs = bean.getImages().split("\\|");//分割images,得到图片数组
        //校验数组大小是否>0,防止空指针
        if (imgs != null && imgs.length > 0) {

            Glide.with(mContext).load(imgs[0]).into(holder.productIv);
        } else {
            holder.productIv.setImageResource(R.mipmap.ic_launcher);
        }
        holder.checkBox.setChecked(bean.isSelected());

        holder.myJIaJianView.setNumEt(bean.getTotalNum());

        holder.myJIaJianView.setJiaJianListener(new MyJIaJianView.JiaJianListener() {
            @Override
            public void getNum(int num) {
                bean.setTotalNum(num);
                if (checkListener!=null){
                    checkListener.notifyParent();//通知一级列表适配器刷新
                }
            }
        });



        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.checkBox.isChecked()) {//选中
                    bean.setSelected(true);
                } else {//非选中
                    bean.setSelected(false);
                }
                if (checkListener!=null){
                    checkListener.notifyParent();//通知一级列表适配器刷新
                }

            }
        });


    }

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

    public class CartViewHolder extends RecyclerView.ViewHolder {
        private CheckBox checkBox;
        private TextView titleTv, priceTv;
        private ImageView productIv;
        private MyJIaJianView myJIaJianView;


        public CartViewHolder(View itemView) {
            super(itemView);
            checkBox = itemView.findViewById(R.id.productCheckbox);
            titleTv =  itemView.findViewById(R.id.title);
            priceTv =itemView.findViewById(R.id.price);
            productIv =itemView.findViewById(R.id.product_icon);
            myJIaJianView =  itemView.findViewById(R.id.jiajianqi);

        }
    }
}

刷新

public interface CartCheckListener {
    void notifyParent();//通知父adapter刷新适配器
}

刷新全部

public  interface CartAllCheckboxListener {
    void notifyAllCheckboxStatus();//通知购物车首页,全选反选按钮是否选中
}

接口

public class Constants {
    public  static final  String GETCARTS = "http://www.zhaoapi.cn/product/getCarts";//获取购物车
    public  static final  String CREATE_ORDER = "https://www.zhaoapi.cn/product/createOrder";//获取购物车
    public  static final  String ADD_CART = "https://www.zhaoapi.cn/product/addCart";//添加购物车

}

M层

public class CartModel {
    Handler handler =new Handler();

    /**
     * 请求购物车数据
     *
     * @param params 参数
     * @param url    请求url
     */
    public void getCarts(HashMap<String, String> params, String url, final CartCallback cartCallback) {

        OkHttpUtils.getInstance().postData(url, params, new RequestCallback() {
            @Override
            public void failure(Call call, IOException e) {

                if (cartCallback != null) {
                    cartCallback.fail("网络有异常,请稍后再试");
                }

            }

            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String jsonResult = response.body().string();
                    if (!TextUtils.isEmpty(jsonResult)) {

                        parseResult(jsonResult, cartCallback);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 解析购物车数据
     *
     * @param jsonResult
     * @param cartCallback
     */
    private void parseResult(String jsonResult, final CartCallback cartCallback) {
        final CartBean cartBean = new Gson().fromJson(jsonResult, CartBean.class);
        if (cartCallback != null && cartBean != null) {//代码规范,代码优化

            handler.post(new Runnable() {
                @Override
                public void run() {
                    cartCallback.success(cartBean);
                }
            });
        }


    }

    public interface CartCallback {
        void success(CartBean cartBean);//回调bean对象给presenter

        void fail(String msg);//异常信息回调
    }

}

P层

public class CartPesenter {
    private CartModel cartModel;
    private IcartView icartView;

    public CartPesenter(IcartView icartView) {
        cartModel =new CartModel();
        attachView(icartView);

    }

    /**
     * 绑定view到presenter
     * @param icartView
     */
    public void attachView(IcartView icartView){
        this.icartView = icartView;
    }

    public void getCarts(HashMap<String,String> params, String url){

        cartModel.getCarts(params, url, new CartModel.CartCallback() {
            @Override
            public void success(CartBean cartBean) {

                if (icartView!=null){
                    icartView.success(cartBean);
                }

            }

            @Override
            public void fail(String msg) {

                if (icartView!=null){
                    icartView.failure(msg);
                }

            }
        });

    }

    /**
     * 解除绑定,把view和presenter解绑,避免内存泄漏
     */
    public void detachView(){
        this.icartView = null;
    }
}

OKHttpUtils

package com.bawei.gouwuche.utils;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by _ヽ陌路离殇ゞ on 2018/8/24.
 */

public class OkHttpUtils {
    //
    private static OkHttpUtils okHttpUtils;
    private OkHttpClient okHttpClient;


    //构造方法私有的?因为不能被调用者new的对象,只能给自己new
    private OkHttpUtils() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new MyInterceptor())//添加拦截器
                .addInterceptor(httpLoggingInterceptor)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5,TimeUnit.SECONDS)
                .build();


    }

    /**
     * public 暴露给调用者,双重检验锁
     *
     * @return
     */
    public static OkHttpUtils getInstance() {
        if (okHttpUtils == null) {
            synchronized (OkHttpUtils.class) {
                if (okHttpUtils == null) {
                    okHttpUtils = new OkHttpUtils();
                }
            }
        }
        return okHttpUtils;
    }


    /**
     * get封装
     *
     * @param params
     * @param url
     * @param requestCallback
     */
    public void getData(String url, HashMap<String, String> params, final RequestCallback requestCallback) {

        StringBuilder urlsb = new StringBuilder();
        String allUrl = "";
        for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
            urlsb.append("?").append(stringStringEntry.getKey()).append("=").append(stringStringEntry.getValue()).append("&");
        }

        allUrl = url + urlsb.toString().substring(0, urlsb.length() - 1);
        System.out.println("url:" + allUrl);

        final Request request = new Request.Builder()
                .url(allUrl).get().build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, IOException e) {
                if (requestCallback != null) {
                    requestCallback.failure(call, e);
                }

            }

            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (requestCallback != null) {
                    requestCallback.onResponse(call, response);
                }

            }
        });
    }

    /**
     * post请求方式
     *
     * @param url
     * @param prams
     */
    public void postData(String url, HashMap<String, String> prams, final RequestCallback requestCallback) {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();

        if (prams != null && prams.size() > 0) {
            for (Map.Entry<String, String> stringStringEntry : prams.entrySet()) {

                formBodyBuilder.add(stringStringEntry.getKey(), stringStringEntry.getValue());
            }
        }

        Request request = new Request.Builder()
                .url(url).post(formBodyBuilder.build()).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (requestCallback != null) {
                    requestCallback.failure(call, e);
                }

            }

            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (requestCallback != null) {
                    requestCallback.onResponse(call, response);
                }

            }
        });
    }


    /**
     * 封装上传文件
     *
     * @param url
     * @param params
     */
    public void uploadFile(String url, HashMap<String, Object> params, final RequestCallback requestCallback) {

//        OkHttpClient okHttpClient1 = new OkHttpClient();
        //多表单上传的的请求体对象,multipart/form-data
        MultipartBody.Builder builder1 = new MultipartBody.Builder();
        builder1.setType(MultipartBody.FORM);//设置上传类型是表单形式




        //1。字符串key,value,2。文件key,value
        for (Map.Entry<String, Object> stringObjectEntry : params.entrySet()) {

            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();

            if (value instanceof File){//如果value类型是文件类型
                File file = (File) value;
                //创建文件请求体
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                builder1.addFormDataPart(key,file.getName(),requestBody);
            }else {
                builder1.addFormDataPart(key, (String) value);
            }
        }

        Request request1 = new Request.Builder().addHeader("","").post(builder1.build()).url(url).build();


        okHttpClient.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (requestCallback != null) {
                    requestCallback.failure(call, e);
                }

                URLEncoder.encode("url");

            }

            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (requestCallback != null) {
                    requestCallback.onResponse(call, response);
                }

            }
        });

    }
}

callback

public interface RequestCallback {
    void failure(Call call, IOException e);
    void onResponse(Call call, Response response);
}

请求成功

public interface IcartView {
    void success(CartBean cartBean);//请求成功
    void failure(String msg);//请求失败
}

流失布局自定义

public class CustomView extends ViewGroup{
    private int mleftMargin=20;
    private int mtopMargin=20;

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

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);

        int leftMargin = mleftMargin;
        int topMargin = mtopMargin;

        int viewHeight = 0;
        int viewWidth = 0;

        //父控件传进来的宽度和高度以及对应的测量模式
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        switch (modeHeight){
            case MeasureSpec.AT_MOST:
                int measuredHeight = 0;
                for (int j = 0; j < getChildCount(); j++) {
                    int measuredWidth = getChildAt(j).getMeasuredWidth();
                    measuredHeight = getChildAt(j).getMeasuredHeight();
                    if (leftMargin+measuredWidth+mleftMargin>getWidth()){
                        leftMargin=mleftMargin;
                        topMargin+=measuredHeight+mtopMargin;
                    }
                    leftMargin+=measuredWidth+mleftMargin;
                }
                topMargin+=measuredHeight+mtopMargin;
                break;
        }
        setMeasuredDimension(sizeWidth,topMargin);
    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        int leftMargin = mleftMargin;
        int topMargin = mtopMargin;

        for (int j = 0; j < getChildCount(); j++) {
            int measuredWidth = getChildAt(j).getMeasuredWidth();
            int measuredHeight = getChildAt(j).getMeasuredHeight();
            if (leftMargin+measuredWidth+mleftMargin>getWidth()){
                leftMargin=mleftMargin;
                topMargin+=measuredHeight+mtopMargin;
                getChildAt(j).layout(leftMargin,topMargin,leftMargin+measuredWidth,topMargin+measuredHeight);
            }else {
                getChildAt(j).layout(leftMargin,topMargin,leftMargin+measuredWidth,topMargin+measuredHeight);
            }
            leftMargin+=measuredWidth+mleftMargin;
        }
    }
}

加减自定义

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.jia_jian_layout,this,true);
//        addView(view);
        jiantv = (TextView) view.findViewById(R.id.jian);
        jiaTv = (TextView) view.findViewById(R.id.jia);
        numEt = (EditText) 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);
                }
            }
        });
    }

    /**
     * 设置editext数量
     * @param
     */
    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);
    }
}

加减

<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>

shape

<shape xmlns:android="http://schemas.android.com/apk/res/android">


    <solid android:color="#C0C0C0" />

    <stroke
        android:width="1dip"
        android:color="#C0C0C0" />

    <padding
        android:bottom="5dp"
        android:left="12dp"
        android:right="12dp"
        android:top="5dp" />

    <corners android:radius="80dp" />
</shape>

依赖

    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    compile 'com.github.bumptech.glide:glide:3.8.0'
    implementation 'com.google.code.gson:gson:2.2.4'
    compile 'com.jcodecraeer:xrecyclerview:1.3.2'

猜你喜欢

转载自blog.csdn.net/qq_42821177/article/details/82026655
今日推荐