Zhou-Kao2

apiservice:

 

 

布局:
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/parent_RecyclerView"
        android:layout_weight="9"
        android:layout_width="match_parent"
        android:layout_height="0dp"></android.support.v7.widget.RecyclerView>

    <LinearLayout
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="0dp">

        <CheckBox
            android:id="@+id/cb_all"
            android:text="全选"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/all_price"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:text="总价¥0.00"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/btn_jiesuan"
            android:text="去结算"
            android:textColor="@color/colorAccent"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />
    </LinearLayout>


</LinearLayout>




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

    <CheckBox
        android:id="@+id/cb_child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/img_child"
        android:layout_width="100dp"
        android:layout_height="100dp" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_weight="2"
        android:layout_width="0dp"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/name_child"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/price_child"
            android:layout_marginTop="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <com.bawei.gwc2019127.ZDYView
        android:id="@+id/zdy_view"
        android:layout_marginTop="30dp"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"/>

</LinearLayout>


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

    <CheckBox
        android:id="@+id/cb_parent"
        android:text="三只松鼠"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/child_RecyclerView"
        android:layout_marginLeft="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

</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_height="wrap_content">

    <Button
        android:id="@+id/btn_jia"
        android:text="+"
        android:padding="5dp"
        android:layout_width="30dp"
        android:layout_height="30dp" />

    <TextView
        android:id="@+id/count"
        android:padding="10dp"
        android:text="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_jian"
        android:text="-"
        android:padding="5dp"
        android:layout_width="30dp"
        android:layout_height="30dp" />

</LinearLayout>

自定义加减器:

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<IView>{
        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<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        String shoppingString = responseBody.string();
                        callBack.getResult(shoppingString);
                    }
                });
    }
}




present层:
public class PresenterImpl implements Contract.IPresenter<Contract.IView>{

    private WeakReference<Contract.IView> 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<String,String> 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<Map.Entry<String, String>> entrySet = params.entrySet();
        for (Map.Entry<String,String> 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<ShopCartBean.OrderDataBean.CartlistBean,BaseViewHolder> {

    public MyChildAdapter(int layoutResId, @Nullable List<ShopCartBean.OrderDataBean.CartlistBean> 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<ShopCartBean.OrderDataBean,BaseViewHolder> {
    public MyParentAdapter(int layoutResId, @Nullable List<ShopCartBean.OrderDataBean> 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<ShopCartBean.OrderDataBean> 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<ShopCartBean.OrderDataBean>) 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);
                }
            }
        });

    }
}

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值