Zhou-Kao2

apiservice:

Zhou-Kao2_第1张图片

 

 

布局:



    

    

        
        
        

自定义加减器:

public class ZDYView extends LinearLayout implements View.OnClickListener {

    private final Button btn_jia;
    private final Button btn_jian;
    private final TextView tvCount;
    private int count = 1;
    public ZDYView(Context context, @Nullable AttributeSet attrs) {

        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.zdy_layout,this,true);
        btn_jia = findViewById(R.id.btn_jia);
        btn_jian = findViewById(R.id.btn_jian);
        tvCount = findViewById(R.id.count);
        btn_jia.setOnClickListener(this);
        btn_jian.setOnClickListener(this);
    }

    public void setText(int i){
        count = 1;
        tvCount.setText(i+"");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_jia:
                count++;
                if (count<=999){
                    tvCount.setText(count+"");
                    myInter.getNumber(count);
                }else {
                    count = 999;
                }
                break;
            case R.id.btn_jian:
                count--;
                if (count>=1){
                    tvCount.setText(count+"");
                    myInter.getNumber(count);
                }else {
                    count=1;
                    Toast.makeText(getContext(), "参数不能小于1", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    public interface MyInter{
        void getNumber(int count);
    }
    MyInter myInter;

    public void setMyInter(MyInter myInter){
        this.myInter = myInter;
    }
}

 

MVP:

契约类:
public interface Contract {
    interface IView{
        void getView(String shoppingString);
    }


    interface IModel{
        void requestData(CallBack callBack);
        interface CallBack{
            void getResult(String shoppingString);
        }
    }


    interface IPresenter{
        void attachView(IView iView);
        void detachView();
    }

}



model层:
public class ModeImpl implements Contract.IModel{
    @Override
    public void requestData(final CallBack callBack) {
        Retrofit retrofit = new Retrofit.Builder().addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(RetrofitManager.SHOPPINGCART).build();

        ApiService apiService = retrofit.create(ApiService.class);
        apiService.shopping().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        String shoppingString = responseBody.string();
                        callBack.getResult(shoppingString);
                    }
                });
    }
}




present层:
public class PresenterImpl implements Contract.IPresenter{

    private WeakReference weakReference;
    private ModeImpl mode;
    @Override
    public void attachView(final Contract.IView iView) {
        weakReference = new WeakReference<>(iView);
        mode = new ModeImpl();

        mode.requestData(new Contract.IModel.CallBack() {
            @Override
            public void getResult(String shoppingString) {
                Contract.IView iView1 = weakReference.get();
                iView.getView(shoppingString);
            }
        });

    }

    @Override
    public void detachView() {

        weakReference.clear();
    }
}

工具类:

public class Head implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        builder.header("userId","2818");
        builder.header("sessionId","15726622336582818");
        Request newRequest = builder.build();
        Response response = chain.proceed(newRequest);
        return response;
    }
}




public class RetrofitUtil {
    private static RetrofitUtil instance = null;
    private Retrofit retrofit;
    private RetrofitUtil(){
        retrofit = new Retrofit.Builder().baseUrl("http://172.17.8.100/small/")
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(OkhttpManager.getInstance().getOkHttpClient())
                .build();
    }

    public static RetrofitUtil getInstance(){
        if (instance == null){
            instance = new RetrofitUtil();
        }
        return instance;
    }

    public Retrofit getRetrofit(){
        return retrofit;
    }
}




public class OkhttpManager {
    // TODO: 2019/12/7  声明一个静态实例
    public static OkhttpManager instance = new OkhttpManager();
    private OkHttpClient okHttpClient;
    private Handler handler = new Handler();

    // TODO: 2019/12/7  构造方法私有化
    private OkhttpManager(){
        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(5000,TimeUnit.MILLISECONDS)
                .writeTimeout(5000,TimeUnit.MILLISECONDS)
                .connectTimeout(5000,TimeUnit.MILLISECONDS)
                .addInterceptor(new Head())
                .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        if (message.startsWith("{") || message.startsWith("[")){
                            Logger.json(message);
                        }else {
                            Logger.d(message);
                        }
                    }
                }).setLevel(HttpLoggingInterceptor.Level.BODY)).build();
    }

    public static OkhttpManager getInstance(){
        return instance;
    }

    // TODO: 2019/11/12  暴露get方法
    public void doGet(String path, final DataCallBack callBack){
        // TODO: 2019/11/12  默认就是get 请求
        Request.Builder builder = new Request.Builder();
        builder.url(path);
        Request request = builder.build();
        // TODO: 2019/11/12  返回一个call对象,okhttp把每次请求都封装成一个call对象
        Call call = okHttpClient.newCall(request);
        // TODO: 2019/11/12  执行异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // TODO: 2019/11/12  请求失败的回调,回调是在子线程中
                final String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onError(message);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // TODO: 2019/11/12  请求成功的回调,回调在子线程中
                // TODO: 2019/11/12  获取json数据
                ResponseBody body = response.body();
                final String json = body.string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onSuccess(json);
                    }
                });
            }
        });
    }

    // TODO: 2019/11/12  暴露dopost方法,post普通表单
    public void doPost(String path, Map params, final DataCallBack callBack){
        // TODO: 2019/11/12  创建request.builder
        Request.Builder builder = new Request.Builder();
        builder.url(path);

        FormBody.Builder form = new FormBody.Builder();
        // TODO: 2019/11/12  遍历map,获取map中所有key和value
        Set> entrySet = params.entrySet();
        for (Map.Entry entry:entrySet){
            String key = entry.getKey();
            String value = entry.getValue();
            // TODO: 2019/11/12  把key和value加入到表单中
            form.add(key,value);
        }
        FormBody body = form.build();
        builder.post(body);

        Request request = builder.build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                final String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onError(message);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody responseBody = response.body();
                final String json = responseBody.string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        callBack.onSuccess(json);
                    }
                });
            }
        });
    }

    public OkHttpClient getOkHttpClient() {

        return okHttpClient;
    }



    // TODO: 2019/11/13  暴露一个接口
    public interface DataCallBack{
        // TODO: 2019/11/13  成功
        void onSuccess(String data);

        // TODO: 2019/11/13  失败
        void onError(String msg);
    }
}

适配器:

public class MyChildAdapter extends BaseQuickAdapter {

    public MyChildAdapter(int layoutResId, @Nullable List data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, final ShopCartBean.OrderDataBean.CartlistBean item) {

        ImageView img_child = helper.getView(R.id.img_child);
        //图片
        Glide.with(mContext).load(item.getDefaultPic())
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
                .placeholder(R.mipmap.ic_launcher)
                .error(R.drawable.ic_launcher_background)
                .into(img_child);
        //商品复选框
        final CheckBox cb_child = helper.getView(R.id.cb_child);
        //商品复选框状态
        cb_child.setChecked(item.innerSelector);
        //商品名称
        helper.setText(R.id.name_child,item.getProductName());
        //商品价格
        helper.setText(R.id.price_child,item.getPrice()+"");
        //加减器
        ZDYView zdy_view = helper.getView(R.id.zdy_view);
        //加减器接口回调
        zdy_view.setMyInter(new ZDYView.MyInter() {
            @Override
            public void getNumber(int count) {
                item.setInCount(count);
                //接口回调
                onIsClick.getCheck();
            }
        });
        cb_child.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //接口回调
                onIsClick.getCheck();
            }
        });
        cb_child.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb_child.isChecked()) {
                    item.setInnerSelector(true);
                }else {
                    item.setInnerSelector(false);
                }
                //接口回调
                onIsClick.getCheck();
            }
        });

    }
    //创建接口
    public interface OnIsClick{
        void getCheck();
    }
    OnIsClick onIsClick;

    public void setOnIsClick(OnIsClick onIsClick) {
        this.onIsClick = onIsClick;
    }
}








public class MyParentAdapter extends BaseQuickAdapter {
    public MyParentAdapter(int layoutResId, @Nullable List data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, final ShopCartBean.OrderDataBean item) {
        // TODO: 2019/12/7  商家名称
        helper.setText(R.id.cb_parent,item.getShopName());
        // TODO: 2019/12/7  商家的复选框
        final CheckBox cb_parent = helper.getView(R.id.cb_parent);
        // TODO: 2019/12/7  设置商家选中状态
        cb_parent.setChecked(item.outterSelector);
        // TODO: 2019/12/7  商品的列表控件
        RecyclerView child_RecyclerView = helper.getView(R.id.child_RecyclerView);
        // TODO: 2019/12/7  线性布局
        LinearLayoutManager manager = new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false);
// TODO: 2019/12/7  设置线性布局
        child_RecyclerView.setLayoutManager(manager);
        // TODO: 2019/12/7  商品适配器
        final MyChildAdapter myChildAdapter = new MyChildAdapter(R.layout.child_item, item.getCartlist());
        child_RecyclerView.setAdapter(myChildAdapter);
        cb_parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断商家当前的选中状态
                if (cb_parent.isChecked()) {
                    //如果商家是选中状态就给他true
                    item.setOutterSelector(true);
                    //遍历商品集合给每个商品true
                    for (int i = 0; i < item.getCartlist().size(); i++) {
                        item.getCartlist().get(i).setInnerSelector(true);
                    }
                }else {
                    //如果商家是选中状态就给他false
                    item.setOutterSelector(false);
                    //遍历商品集合给每个商品false
                    for (int i = 0; i < item.getCartlist().size(); i++) {
                        item.getCartlist().get(i).setInnerSelector(false);
                    }
                }
                //刷新适配器
                myChildAdapter.notifyDataSetChanged();
                //接口回调
                onOutClick.getCheck();
            }
        });

        //商家复选框状态改变监听
        cb_parent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //接口回调
                onOutClick.getCheck();
            }
        });
        //商品适配器回调
        myChildAdapter.setOnIsClick(new MyChildAdapter.OnIsClick() {
            @Override
            public void getCheck() {
                boolean issetCheck = true;
                for (int i = 0; i < item.getCartlist().size(); i++) {
                    issetCheck = issetCheck&item.getCartlist().get(i).getInnerSelector();
                }
                cb_parent.setChecked(issetCheck);
                item.setOutterSelector(issetCheck);
                //接口回调
                onOutClick.getCheck();
            }
        });

    }
    //创建接口
    public interface OnOutClick{
        void getCheck();
    }
    OnOutClick onOutClick;

    public void setOnOutClick(OnOutClick onOutClick){
        this.onOutClick = onOutClick;
    }

}

主方法:

public class MainActivity extends AppCompatActivity implements Contract.IView {


    @BindView(R.id.parent_RecyclerView)
    RecyclerView parentRecyclerView;
    @BindView(R.id.cb_all)
    CheckBox cbAll;
    @BindView(R.id.all_price)
    TextView allPrice;
    @BindView(R.id.btn_jiesuan)
    Button btnJiesuan;
    private Unbinder unbinder;
    private PresenterImpl presenter;
    //商家适配器
    private MyParentAdapter myParentAdapter;
    //商家集合
    private ArrayList shoppingCartBeanOrderData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        unbinder = ButterKnife.bind(this);
        presenter = new PresenterImpl();
        presenter.attachView(this);

    }
    //点击
    @OnClick({R.id.cb_all, R.id.btn_jiesuan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cb_all:
                if (cbAll.isChecked()) {
                    for (int i = 0; i < shoppingCartBeanOrderData.size(); i++) {
                        shoppingCartBeanOrderData.get(i).setOutterSelector(true);
                        for (int j = 0; j < shoppingCartBeanOrderData.get(i).getCartlist().size(); j++) {
                            shoppingCartBeanOrderData.get(i).getCartlist().get(j).setInnerSelector(true);
                        }
                    }
                }else {
                    for (int i = 0; i < shoppingCartBeanOrderData.size(); i++) {
                        shoppingCartBeanOrderData.get(i).setOutterSelector(false);
                        for (int j = 0; j < shoppingCartBeanOrderData.get(i).getCartlist().size(); j++) {
                            shoppingCartBeanOrderData.get(i).getCartlist().get(j).setInnerSelector(false);
                        }
                    }
                }
                //刷新适配器
                myParentAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_jiesuan:
                break;
        }
    }
    //有数据
    @Override
    public void getView(String shoppingString) {
        //解析
        Gson gson = new Gson();
        ShopCartBean shoppingCartBean = gson.fromJson(shoppingString, ShopCartBean.class);
        shoppingCartBeanOrderData = (ArrayList) shoppingCartBean.getOrderData();
        //设置线性布局
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        parentRecyclerView.setLayoutManager(manager);
        //创建适配器
        myParentAdapter = new MyParentAdapter(R.layout.parent_item, shoppingCartBeanOrderData);
        //设置适配器
        parentRecyclerView.setAdapter(myParentAdapter);

        myParentAdapter.setOnOutClick(new MyParentAdapter.OnOutClick() {
            @Override
            public void getCheck() {
                boolean isCheck = true;
                int sum = 0;
                for (int i = 0; i < shoppingCartBeanOrderData.size(); i++) {
                    isCheck = isCheck & shoppingCartBeanOrderData.get(i).getOutterSelector();
                    for (int j = 0; j < shoppingCartBeanOrderData.get(i).getCartlist().size(); j++) {
                        int inCount = shoppingCartBeanOrderData.get(i).getCartlist().get(j).getInCount();
                        int price = shoppingCartBeanOrderData.get(i).getCartlist().get(j).getPrice();
                        boolean innerSelector = shoppingCartBeanOrderData.get(i).getCartlist().get(j).getInnerSelector();
                        isCheck = isCheck & innerSelector;
                        if (innerSelector) {
                            sum += inCount * price;
                        }
                    }
                    allPrice.setText(sum + "");
                    cbAll.setChecked(isCheck);
                }
            }
        });

    }
}

 

 

 

 

 

 

 

你可能感兴趣的:(Zhou-Kao2)