购物车(map,一级列表,view绘制加减号)

//权限

  <uses-permission android:name="android.permission.INTERNET"/>

//依赖

 compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
    compile 'com.github.bumptech.glide:glide:3.7.0'

//主布局文件

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!--头布局-->
    <LinearLayout
        android:id="@+id/top_bar"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="#f7f7f7"
        android:orientation="vertical" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:background="@android:color/transparent"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/back"
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:layout_alignParentLeft="true"
                android:layout_gravity="center_vertical"
                android:padding="12dp"
                android:src="@drawable/back" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:minHeight="48dp"
                android:text="购物车"
                android:textColor="#1a1a1a"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/edit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="40dp"
                android:gravity="center"
                android:minHeight="48dp"
                android:text="编辑"
                android:textColor="#1a1a1a"
                android:textSize="14sp" />
        </RelativeLayout>
    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:childIndicator="@null"
        android:groupIndicator="@null" >
    </ListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <CheckBox
            android:id="@+id/all_chekbox"
            android:layout_marginLeft="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全选"/>
        <LinearLayout
            android:id="@+id/ll_info"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginRight="20dp"
                android:layout_weight="1"
                >
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:gravity="right"
                    >
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:text="合计:"
                        android:textSize="18sp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/total_price"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="¥0.00"
                        android:textColor="#f23232"
                        android:textSize="16sp"
                        android:textStyle="bold" />
                </LinearLayout>
                <TextView
                    android:id="@+id/total_number"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="共有商品:0件"
                    android:gravity="right"
                    android:textSize="16sp"
                    android:textStyle="bold" />
            </LinearLayout>
            <TextView
                android:id="@+id/tv_go_to_pay"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="3"
                android:background="#fd7a05"
                android:clickable="true"
                android:gravity="center"
                android:text="结算"
                android:textColor="#FAFAFA"

                />
        </LinearLayout>

    </LinearLayout>
</LinearLayout>

//子布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="230dp"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/child_checkbox"
        android:layout_marginTop="50dp"
        android:layout_marginLeft="20dp"
        android:layout_marginBottom="50dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <RelativeLayout
        android:layout_marginLeft="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/shop_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginLeft="17dp"
            android:layout_marginStart="17dp"
            android:text="TextView"
            android:layout_alignParentTop="true" />

        <ImageView
            android:id="@+id/shop_img"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_marginTop="30dp"
            app:srcCompat="@mipmap/ic_launcher"
            android:layout_below="@+id/shop_title"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <TextView
            android:id="@+id/shop_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/shop_img"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:text="¥20"
            android:textColor="#f23232"/>

        <com.bwei.listview.myview.AddDeleteView
            android:id="@+id/adv"
            android:layout_width="160dp"
            android:layout_height="30dp"
            android:layout_below="@+id/shop_price"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="140dp"
            app:left_text="-"
            app:right_text="+"
            app:middle_text="1"
            android:focusable="false"
            >

        </com.bwei.listview.myview.AddDeleteView>

        <Button
            android:id="@+id/shop_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:visibility="invisible"
            android:text="删除" />
    </RelativeLayout>


</LinearLayout>


//绘制加减号布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="1">

    <TextView
        android:id="@+id/txt_delete"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:text="-"
        android:gravity="center"
        android:background="#8b948b"/>

    <EditText
        android:id="@+id/et_number"
        android:layout_marginTop="2dp"
        android:layout_width="50dp"
        android:layout_height="30dp"
        android:background="@drawable/edit"
        android:layout_weight="0.00"
        android:gravity="center"
        android:text="1"/>
    <TextView
        android:id="@+id/txt_add"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:text="+"
        android:gravity="center"
        android:background="#8b948b"/>


</LinearLayout>

//在value下创建attrs.xml用来实现加减号颜色等等

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="AddDeleteViewStyle">
        <attr name="left_text" format="string"></attr>
        <attr name="right_text" format="string"></attr>
        <attr name="middle_text" format="string"></attr>
        <attr name="left_text_color" format="color"></attr>
    </declare-styleable>
</resources>

//在drawable下面添加"<"这个样子的图片,在创建edit.xml

//edit.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF" />
    <!--<corners android:radius="3dip"/>-->
    <stroke
        android:width="1dip"
        android:color="#BDC7D8" />
</shape>

//Bean类

public class GoodsBean {

    private String childTitle;
    private boolean checkchild;
    private String img;
    private double price;
    private int num;
    private boolean btn;

    public GoodsBean(String childTitle, boolean checkchild, String img, double price, int num, boolean btn) {
        this.childTitle = childTitle;
        this.checkchild = checkchild;
        this.img = img;
        this.price = price;
        this.num = num;
        this.btn = btn;
    }

    public String getChildTitle() {
        return childTitle;
    }

    public void setChildTitle(String childTitle) {
        this.childTitle = childTitle;
    }

    public boolean isCheckchild() {
        return checkchild;
    }

    public void setCheckchild(boolean checkchild) {
        this.checkchild = checkchild;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public boolean isBtn() {
        return btn;
    }

    public void setBtn(boolean btn) {
        this.btn = btn;
    }

    @Override
    public String toString() {
        return "GoodsChilde{" +
                "childTitle='" + childTitle + '\'' +
                ", checkchild=" + checkchild +
                ", img='" + img + '\'' +
                ", price=" + price +
                ", num=" + num +
                ", btn=" + btn +
                '}';
    }
}

//m层

public class HttpUtils {
    private static volatile HttpUtils instance;

    private static Handler handler = new Handler();

    private HttpUtils(){

    }
    public static HttpUtils getInstance() {
        if (instance == null) {
            synchronized (HttpUtils.class) {
                if (instance == null) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }
    //get请求
    public void get(String url, Map<String,String> map, final CallBack callBack, final Class c,String tag){
        //对url和参数做拼接处理
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(url);
        //判断是否存在?   if中是存在
        if(stringBuffer.indexOf("?")!=-1 ){
            //判断?是否在最后一位    if中是不在最后一位
            if(stringBuffer.indexOf("?")!=stringBuffer.length()-1){
                stringBuffer.append("&");
            }
        }else{
            stringBuffer.append("?");
        }
        for(Map.Entry<String,String> entry:map.entrySet()){
            stringBuffer.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }
        //判断是否存在&   if中是存在
        if(stringBuffer.indexOf("&")!=-1){
            stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("&"));
        }

        //1:创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        //2:创建Request对象
        final Request request = new Request.Builder()
                .get()
                .url(stringBuffer.toString())
                .build();
        //3:创建Call对象
        Call call = okHttpClient.newCall(request);
        //4:请求网络
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(e);
                    }
                });
            }
            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("TAG",result.toString());
                //拿到数据解析
                final Object o = new Gson().fromJson(result, c);
                Log.i("hhh", o+"");
                //当前是在子线程,回到主线程中
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //回调
                        callBack.onSuccess("hh",o);
                    }
                });
            }
        });

    }
    //post请求
    public void post(String url, Map<String,String> map, final CallBack callBack, final Class c,String tag){
        //1:创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2:提供post请求需要的body对象
        FormBody.Builder builder = new FormBody.Builder();
        for(Map.Entry<String,String> entry:map.entrySet()){
            builder.add(entry.getKey(),entry.getValue());
        }
        FormBody body = builder.build();
        //3:创建Request对象
        final Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        //4:创建Call对象
        Call call = okHttpClient.newCall(request);
        //5:请求网络
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(e);
                    }
                });
            }
            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                //拿到数据解析
                final Object o = new Gson().fromJson(result, c);
                //当前是在子线程,回到主线程中
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //回调
                        callBack.onSuccess("hh",o);
                    }
                });
            }
        });
    }

}

//m层调用的CallBack接口

public interface CallBack {

    void onSuccess(String tag,Object o);

    void onFailed(Exception e);
}

//v层

public interface Iv {
    void onSuccess(List<GoodsBean> list);
    void onFiled( Exception e);
}

//p层

public class Presenter {
    private Context context;
    private Iv iv;
    private List<GoodsBean> list;

    public Presenter(Context context, Iv iv, List<GoodsBean> list) {
        this.context = context;
        this.iv = iv;
        this.list = list;
    }

    public void Goods() {
        HashMap<String, String> map = new HashMap<>();
        HttpUtils.getInstance().post("http://120.27.23.105/product/getCarts?uid=100", map, new CallBack() {
            @Override
            public void onSuccess(String tag, Object o) {
                Bean bean = (Bean) o;
                List<Bean.DataBean> data = bean.getData();
                 for(int i=0;i<data.size();i++){
                     List<Bean.DataBean.ListBean> list1 = data.get(i).getList();
                     for(int j=0;j<list1.size();j++){
                         double price = list1.get(j).getBargainPrice();
                         String images = list1.get(j).getImages();
                         String title = list1.get(j).getTitle();
                         list.add(new GoodsBean(title,false,images,price,1,false));
                     }
                     Log.e("hhh", list.toString());
                 }
                iv.onSuccess(list);

            }

            @Override
            public void onFailed(Exception e) {

            }
        },Bean.class,"hh");
    }

    }

//绘制的加减号的class

public class AddDeleteView extends LinearLayout {
    private OnAddDelClickListener listener;
    private EditText etNumber;

    //对外提供一个点击的回调接口
    public interface OnAddDelClickListener{
        void onAddClick(View v);
        void onDelClick(View v);
    }

    public void setOnAddDelClickListener(OnAddDelClickListener listener){
        if(listener!=null){
            this.listener=listener;
        }
    }

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

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

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

    private void initView(Context context, AttributeSet attrs, int defStyleAttr) {
        View.inflate(context, R.layout.layout_add_delete,this);

        //获取控件
        TextView txtDelete=findViewById(R.id.txt_delete);
        TextView txtAdd=findViewById(R.id.txt_add);
        etNumber = findViewById(R.id.et_number);


        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AddDeleteViewStyle);

        String leftText = typedArray.getString(R.styleable.AddDeleteViewStyle_left_text);
        String rightText = typedArray.getString(R.styleable.AddDeleteViewStyle_right_text);
        String middleText = typedArray.getString(R.styleable.AddDeleteViewStyle_middle_text);
        int color = typedArray.getColor(R.styleable.AddDeleteViewStyle_left_text_color, Color.BLACK);

        txtDelete.setText(leftText);
        txtAdd.setText(rightText);
        etNumber.setText(middleText);
        txtDelete.setTextColor(color);

        //回收
        typedArray.recycle();


        txtDelete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onDelClick(view);
            }
        });

        txtAdd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onAddClick(view);
            }
        });

    }
    //对外提供一个修改数字的方法
    public void setNumber(int number){
        if(number>0){
            etNumber.setText(number+"");
        }
    }
    //对外提供一个获取当前数字的方法
    public int getNumber(){
        String string = etNumber.getText().toString();
        int i = Integer.parseInt(string);
        return i;
    }
}

//Activity

public class MainActivity extends AppCompatActivity implements Iv {

    private ListView listView;
    public CheckBox all_checKbox;
    private TextView total_price;
    private TextView total_number;
    private TextView pay;
    private TextView edit;
    List<GoodsBean> list = new ArrayList<GoodsBean>();
    private Presenter presenter;
    private GoodsAdapter adapter;


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

        listView = (ListView) findViewById(R.id.listView);
        all_checKbox = (CheckBox) findViewById(R.id.all_chekbox);
        total_price = (TextView) findViewById(R.id.total_price);
        total_number = (TextView) findViewById(R.id.total_number);
        pay = (TextView) findViewById(R.id.tv_go_to_pay);
        edit = (TextView) findViewById(R.id.edit);

        presenter = new Presenter(MainActivity.this, this, list);
        presenter.Goods();
        //全选按钮的点击事件
        all_checKbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取到全选按钮的状态
                boolean checked = all_checKbox.isChecked();
                for (GoodsBean i : list) {
                    i.setCheckchild(checked);
                }

                //刷新适配器
                adapter.notifyDataSetChanged();
                //计算的方法
                changesum(list);
            }

        });
    }

    //计算的逻辑
    public void changesum(List<GoodsBean> goodsbean) {
        double sum = 0;
        int count = 0;
        for (int i = 0; i < goodsbean.size(); i++) {

            boolean childCb1 = goodsbean.get(i).isCheckchild();
            if (childCb1) {
                double price = goodsbean.get(i).getPrice();
                int num = goodsbean.get(i).getNum();
                sum += num * price;
                count += num;

            }
        }
        total_price.setText("¥:" + sum);
        total_number.setText("共计有"+count+"件商品");
    }

    @Override
    public void onSuccess(List<GoodsBean> list) {
        adapter = new GoodsAdapter(this, list);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onFiled(Exception e) {

    }
}

//适配器

public class GoodsAdapter extends BaseAdapter {

    private Context context;
    private List<GoodsBean> list;
    MainActivity con;

    private View view;

    public GoodsAdapter(Context context, List<GoodsBean> list) {
        this.context = context;
        this.list = list;
        con=(MainActivity)context;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
         final ChildViewHolder holder;
        if(view==null){

            holder =new ChildViewHolder();
            view = view.inflate(context, R.layout.ex_child_item, null);
            holder.ch2=view.findViewById(R.id.child_checkbox);//子级的选择框
            holder.title=view.findViewById(R.id.shop_title);//子级的标题
            holder.img=view.findViewById(R.id.shop_img);//图片
            holder.et_number=view.findViewById(R.id.et_number);//加减中间的数量
            holder.price=view.findViewById(R.id.shop_price);//价格
            holder.txt_delete=view.findViewById(R.id.txt_delete);//加减器的减
            holder.txt_add=view.findViewById(R.id.txt_add);//加减器的加
            holder.txt_delete.setText("-");//设置显示减号
            holder.txt_add.setText("+");//设置显示加号
            holder.jiajia=view.findViewById(R.id.adv);//设置显示加减器
            holder.jiajia.setNumber(list.get(i).getNum());//自定义view修改数字的方法
            holder.btn=view.findViewById(R.id.shop_delete);//删除的按钮
            view.setTag(holder);
        }else{
            holder=(ChildViewHolder)view.getTag();

        }
        holder.jiajia.setOnAddDelClickListener(new AddDeleteView.OnAddDelClickListener() {
            @Override
            public void onAddClick(View v) {
                int number = holder.jiajia.getNumber();
                number++;
                holder.jiajia.setNumber(number);
                list.get(i).setNum(number);
                con.changesum(list);//计算的方法
            }

            @Override
            public void onDelClick(View v) {
                int number = holder.jiajia.getNumber();
                number--;
                holder.jiajia.setNumber(number);
                list.get(i).setNum(number);
                con.changesum(list);
            }
        });
        holder.ch2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean checked = holder.ch2.isChecked();
                list.get(i).setCheckchild(checked);
                //获取到Activity
                MainActivity con=(MainActivity)context;
                for(int i=0;i<list.size();i++){
                    boolean checkchild = list.get(i).isCheckchild();
                    if(!checkchild){
                        con.all_checKbox.setChecked(false);
                        break;
                    }else{
                        con.all_checKbox.setChecked(true);
                    }

                }

                con.changesum(list);
            }


        });


        holder.ch2.setChecked(list.get(i).isCheckchild());
        holder.title.setText(list.get(i).getChildTitle());
        String img = list.get(i).getImg();
        String[] split = img.split("\\|");
        Glide.with(context).load(split[0]).into(holder.img);
        holder.price.setText(list.get(i).getPrice()+"");
        return view;
    }
     class ChildViewHolder {
         CheckBox ch2;
         TextView title;
         ImageView img;
         TextView price;
         TextView txt_delete;
         TextView et_number;
         TextView txt_add;
         AddDeleteView jiajia;
         Button btn;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值