欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现购物车功能

程序员文章站 2024-02-17 09:33:10
最近看了一些淘宝购物车的demo,于是也写了一个。 效果图如下: 主要代码如下: actvity中的代码: public class s...

最近看了一些淘宝购物车的demo,于是也写了一个。

效果图如下:

Android实现购物车功能

主要代码如下:
actvity中的代码:

public class shoppingcartactivity extends baseactivity {

  private list<test> data;
  private listview mlistview;
  private shoppingcartadapter adapter;

  private relativelayout rlrefresh;
  private textview tvrefresh;
  private progressbar barrefresh;
  private linearlayout clear;
  private checkbox checkbox_select_all;
  private checkbox checkbox_add;
  private textview integral_sum;
  private int sum = 0;
  private int[] sumintegral;
  private context context;

  @override
  protected void oncreate(bundle bundle) {
    // todo auto-generated method stub
    super.oncreate(bundle);
    setcontentview(r.layout.activity_shopping_cart);
    initview();
  }

  private void initview() {
    context = this;
    showpage = 1;
    ispermitflag = true;
    data = new arraylist<test>();
    // 测试数据
    data.add(new test("id", "color", "type", "100"));
    data.add(new test("id", "color", "type", "200"));
    data.add(new test("id", "color", "type", "300"));
    data.add(new test("id", "color", "type", "0"));
    data.add(new test("id", "color", "type", "300"));
    data.add(new test("id", "color", "type", "100"));
    data.add(new test("id", "color", "type", "500"));
    data.add(new test("id", "color", "type", "0"));
    data.add(new test("id", "color", "type", "900"));

    adapter = new shoppingcartadapter(context, handler, data);

    sumintegral = new int[data.size() + 1];

    checkbox_add = (checkbox) findviewbyid(r.id.checkbox_add);
    integral_sum = (textview) findviewbyid(r.id.integral_sum);
    clear = (linearlayout) findviewbyid(r.id.clear);
    clear.setonclicklistener(new onclicklistener() {

      @override
      public void onclick(view v) {
        data.clear();
        adapter.notifydatasetchanged();
        integral_sum.settext(0 + "");
        checkbox_select_all.setchecked(false);
        checkbox_add.setclickable(false);
      }
    });
    checkbox_select_all = (checkbox) findviewbyid(r.id.checkbox_select);
    checkbox_select_all.setonclicklistener(new onclicklistener() {

      @override
      public void onclick(view v) {

        hashmap<integer, boolean> isselected = shoppingcartadapter
            .getisselected();
        iterator iterator = isselected.entryset().iterator();
        list<boolean> array = new arraylist<boolean>();//列表中checkbox选中状态
        list<integer> nums = new arraylist<integer>();//列表中商品数量
        while (iterator.hasnext()) {
          hashmap.entry entry = (hashmap.entry) iterator.next();
          integer key = (integer) entry.getkey();
          boolean val = (boolean) entry.getvalue();
          array.add(val);
        }
        for (int i = 0; i < data.size(); i++) {
          int num = data.get(i).getnum();
          int integral = integer.valueof(data.get(i).getintegral());
          nums.add(num);
        }
        if (checkbox_select_all.ischecked()) {

          for (int i = 0; i < data.size(); i++) {
            shoppingcartadapter.getisselected().put(i, true);
          }
          checkbox_add.setchecked(true);
          adapter.notifydatasetchanged();
        } else {
          for (int i = 0; i < data.size(); i++) {
            shoppingcartadapter.getisselected().put(i, false);
          }
          checkbox_add.setchecked(false);
          adapter.notifydatasetchanged();
          integral_sum.settext(0 + "");
        }

      }
    });
    mlistview= (listview) findviewbyid(r.id.finance_list);
    mlistview.setadapter(adapter);
    mlistview.setonitemclicklistener(new onitemclicklistener() {

      @override
      public void onitemclick(adapterview<?> parent, view view,
          int position, long id) {
        toast.maketext(context, position + "", toast.length_long)
            .show();

        int pos = position - 1;
        viewholder viewholder = (viewholder) view.gettag();
        int num = data.get(pos).getnum();
        if (num == 0) {
          toast.maketext(context, "请选择商品数量", toast.length_long)
              .show();
        } else {
          boolean cu = !shoppingcartadapter.getisselected().get(pos);
          shoppingcartadapter.getisselected().put(pos, cu);
          adapter.notifydatasetchanged();
          //遍历获取列表中checkbox的选中状态
          hashmap<integer, boolean> isselected = shoppingcartadapter
              .getisselected();
          iterator iterator = isselected.entryset().iterator();
          list<boolean> array = new arraylist<boolean>();
          while (iterator.hasnext()) {
            hashmap.entry entry = (hashmap.entry) iterator.next();
            integer key = (integer) entry.getkey();
            boolean val = (boolean) entry.getvalue();
            array.add(val);
          }
          if (test.isallfalse(array)) {
            checkbox_select_all.setchecked(false);
            checkbox_add.setchecked(false);
          }
          if (test.isalltrue(array)) {
            checkbox_select_all.setchecked(true);
            checkbox_add.setchecked(true);
          }
          if (test.ishaveonefasle(array)) {
            checkbox_select_all.setchecked(false);
          }
          if (test.ishaveonetrue(array)) {
            checkbox_add.setchecked(true);
          }
        }
      }
    });
  }

  @suppresslint("handlerleak")
  private handler handler = new handler(){
    @suppresswarnings("unchecked")
    @override
    public void handlemessage(message msg) {
      super.handlemessage(msg);
      if(msg.what == 10){ //更改选中商品的总价格
        float price = (float)msg.obj;
        if(price > 0){
          integral_sum.settext(price+"");
        }else{
          integral_sum.settext("0");
        }
      }
      else if(msg.what == 11){
        //列表选中状态
        list<boolean> array = (list<boolean>) msg.obj;
        if (test.isallfalse(array)) {
          checkbox_select_all.setchecked(false);
          checkbox_add.setchecked(false);
        }
        if (.isalltrue(array)) {
          checkbox_select_all.setchecked(true);
          checkbox_add.setchecked(true);
        }
        if (test.ishaveonefasle(array)) {
          checkbox_select_all.setchecked(false);
        }
        if (test.ishaveonetrue(array)) {
          checkbox_add.setchecked(true);
        }
      }
    }
  };

actvity中xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:header=http://schemas.android.com/apk/res/com.sxc.test"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/app_background"
  android:orientation="vertical" >

  <com.autoserve.core.widget.headerwidget
    android:id="@+id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignparenttop="true"
    header:text="我的购物车" />

  <linearlayout
    android:id="@+id/layout1"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_below="@id/header"
    android:layout_gravity="center"
    android:layout_margintop="20dp"
    android:background="@color/white"
    android:orientation="horizontal" >

    <linearlayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_marginleft="10dp"
      android:layout_weight="1"
      android:gravity="center_vertical"
      android:orientation="horizontal" >

      <checkbox
        android:id="@+id/checkbox_select"
        style="@style/customcheckboxtheme"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

      <textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginleft="10dp"
        android:text="全选"
        android:textcolor="@color/gry_666666"
        android:textsize="@dimen/small_size" />
    </linearlayout>

    <linearlayout
      android:id="@+id/clear"
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:layout_marginright="20dp"
      android:gravity="center_vertical|right"
      android:orientation="horizontal" >

      <checkbox
        android:layout_width="12dp"
        android:layout_height="12dp"
        android:background="@drawable/clear" />

      <textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginleft="5dp"
        android:text="清空购物车"
        android:textcolor="#b61d1d"
        android:textsize="@dimen/small_size" />
    </linearlayout>
  </linearlayout>

  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/layout1"
    android:layout_marginbottom="50dp"
    android:orientation="vertical" >

    <view
      android:layout_width="match_parent"
      android:layout_height="0.1dp"
      android:background="@color/divider_color" />

    <listview
      android:id="@+id/finance_list"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:clickable="false"
      android:divider="@color/lucency" />

    <include
      layout="@layout/include_refresh"
      android:visibility="gone" />
  </linearlayout>

  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignparentbottom="true"
    android:orientation="horizontal" >

    <linearlayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="2"
      android:background="@color/gry_999999"
      android:gravity="center_vertical"
      android:orientation="horizontal" >

      <linearlayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginleft="5dp"
        android:layout_marginright="5dp"
        android:gravity="center"
        android:orientation="horizontal" >

        <checkbox
          android:id="@+id/checkbox_add"
          style="@style/customcheckboxtheme2"
          android:layout_width="wrap_content"
          android:clickable="false"
          android:layout_height="wrap_content" />
      </linearlayout>

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

        <textview
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="合计:"
          android:textcolor="@color/white"
          android:textsize="@dimen/small_size" />

        <textview
          android:id="@+id/integral_sum"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginleft="5dp"
          android:layout_marginright="5dp"
          android:text="0"
          android:textcolor="@color/theme_color"
          android:textsize="@dimen/small_size" />

        <textview
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="积分"
          android:textcolor="@color/white"
          android:textsize="@dimen/small_size" />
      </linearlayout>
    </linearlayout>

    <textview
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:background="@color/theme_color"
      android:gravity="center"
      android:text="结算"
      android:textcolor="@color/white"
      android:textsize="@dimen/small_size" />
  </linearlayout>

</relativelayout>

-xml中头部可以到网上找一个这里就不放上来了
.checkbox和button的样式可以根据个人喜好设置。

adaper中的代码:

public class shoppingcartadapter extends baseadapter {

  private context context;
  private list<test> loans;
  private layoutinflater inflater;
  private static hashmap<integer, boolean> isselected;
  private static hashmap<integer, integer> numbers;
  private handler handler;
  int num;// 商品数量

  static class viewholder { // 自定义控件集合
    public checkbox ck_select;
    public imageview pic_goods;
    public textview id_goods;
    public textview color_goods;
    public textview type_goods;
    public textview integral_goods;
    public addminuswidget add_minus;
    public linearlayout layout;
    public textview number;
    public button minus;
    public button plus;
  }

  /**
   * 实例化adapter
   * 
   * @param context
   * @param data
   */
  public shoppingcartadapter(context context, handler handler, list<test> data) {
    this.context = context;
    this.inflater = layoutinflater.from(context);
    this.loans = data;
    this.handler = handler;
    isselected = new hashmap<integer, boolean>();
    numbers = new hashmap<integer, integer>();
    initdate();
  }

  private void initdate() {
    for (int i = 0; i < loans.size(); i++) {
      getisselected().put(i, false);
      getnumbers().put(i, 1);
    }
  }

  @override
  public int getcount() {
    return loans.size();
  }

  @override
  public object getitem(int position) {
    return loans.get(position);
  }

  @override
  public long getitemid(int position) {
    return position;
  }

  @override
  public view getview(final int position, view convertview, viewgroup parent) {
    // 自定义视图
    viewholder itemview = null;
    if (convertview == null) {
      // 获取list_item布局文件的视图
      itemview = new viewholder();
      convertview = inflater.inflate(r.layout.list_shopping_cart_item,
          null);
      // 获取控件对象
      itemview.ck_select = (checkbox) convertview
          .findviewbyid(r.id.ck_select);
      itemview.pic_goods = (imageview) convertview
          .findviewbyid(r.id.pic_goods);
      itemview.id_goods = (textview) convertview
          .findviewbyid(r.id.id_goods);
      itemview.color_goods = (textview) convertview
          .findviewbyid(r.id.color_goods);
      itemview.type_goods = (textview) convertview
          .findviewbyid(r.id.type_goods);
      itemview.integral_goods = (textview) convertview
          .findviewbyid(r.id.integral_goods);
      itemview.number = (textview) convertview.findviewbyid(r.id.number);
      itemview.minus = (button) convertview.findviewbyid(r.id.minus);
      itemview.plus = (button) convertview.findviewbyid(r.id.plus);
      convertview.settag(itemview);
    } else {
      itemview = (viewholder) convertview.gettag();
    }

    init(itemview, position);

    itemview.ck_select.setchecked(getisselected().get(position));
    itemview.number.settext(getnumbers().get(position).tostring());
    if (getisselected().get(position)) {
      itemview.ck_select.setchecked(true);
    } else {
      itemview.ck_select.setchecked(false);
    }

    string a = itemview.number.gettext().tostring();
    loans.get(position).setnum(integer.valueof(a));

    test test = loans.get(position);
    itemview.id_goods.settext((charsequence) test.getid());
    itemview.color_goods.settext((charsequence) test.getcolor());
    itemview.type_goods.settext((charsequence) test.gettype());
    itemview.integral_goods.settext((charsequence) test.getintegral());
    itemview.pic_goods.setimageresource(r.drawable.shopping);
    return convertview;
  }

  private void init(final viewholder itemview, final int position) {

    itemview.ck_select
        .setoncheckedchangelistener(new oncheckedchangelistener() {

          @override
          public void oncheckedchanged(compoundbutton buttonview,
              boolean ischecked) {
            isselected.put(position, true);
            getisselected().put(position, ischecked);
            itemview.ck_select.setchecked(getisselected().get(
                position));
            handler.sendmessage(handler.obtainmessage(10,
                gettotalprice()));

            iterator iterator = isselected.entryset().iterator();
            list<boolean> array = new arraylist<boolean>();
            while (iterator.hasnext()) {
              hashmap.entry entry = (hashmap.entry) iterator
                  .next();
              integer key = (integer) entry.getkey();
              boolean val = (boolean) entry.getvalue();
              array.add(val);
            }
            handler.sendmessage(handler.obtainmessage(11, array));
          }
        });

    final string numstring = itemview.number.gettext().tostring();
    itemview.plus.setonclicklistener(new onclicklistener() {

      @override
      public void onclick(view v) {

        if (numstring == null || numstring.equals("")) {
          num = 1;
          itemview.number.settext("1");
        } else {
          if (++num < 1) // 先加,再判断
          {
            num--;

            toast.maketext(context, "请输入一个大于0的数字",
                toast.length_short).show();
          } else {
            itemview.number.settext(string.valueof(num));
            loans.get(position).setnum(num);
            numbers.put(position, num);
            handler.sendmessage(handler.obtainmessage(10,
                gettotalprice()));
            log.i("test", "+:" + num);
          }
        }
      }
    });
    itemview.minus.setonclicklistener(new onclicklistener() {

      @override
      public void onclick(view v) {

        if (numstring == null || numstring.equals("")) {
          num = 1;
          itemview.number.settext("1");
        } else {
          if (--num < 1) // 先加,再判断
          {
            num++;
            log.i("test", "-:" + num);
            toast.maketext(context, "请输入一个大于0的数字",
                toast.length_short).show();
            log.i("test", "-:" + num);
          } else {
            itemview.number.settext(string.valueof(num));
            log.i("test", "-:" + num);
            loans.get(position).setnum(num);
            numbers.put(position, num);
            handler.sendmessage(handler.obtainmessage(10,
                gettotalprice()));
          }
        }

      }
    });

  }

  /**
   * 计算选中商品的积分
   * 
   * @return 返回需要付费的总积分
   */
  private float gettotalprice() {
    test bean = null;
    float totalprice = 0;
    for (int i = 0; i < loans.size(); i++) {
      bean = loans.get(i);
      if (shoppingcartadapter.getisselected().get(i)) {
        totalprice += bean.getnum()
            * integer.valueof(bean.getintegral());
      }
    }
    return totalprice;
  }

  public static hashmap<integer, boolean> getisselected() {
    return isselected;
  }

  public static void setisselected(hashmap<integer, boolean> isselected) {
    shoppingcartadapter.isselected = isselected;
  }

  public static hashmap<integer, integer> getnumbers() {
    return numbers;
  }

  public static void setnumbers(hashmap<integer, integer> numbers) {
    shoppingcartadapter.numbers = numbers;
  }
}

adapter中的xml代码:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:descendantfocusability="blocksdescendants"
  android:background="@color/white"

  android:orientation="vertical" >
  <view
    android:layout_width="match_parent"
    android:layout_height="0.1dp"
    android:background="@color/divider_color" />

  <linearlayout
    android:id="@+id/layout5"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="5dp" >

    <checkbox
      android:id="@+id/ck_select"
      style="@style/customcheckboxtheme"
      android:layout_width="wrap_content"
      android:focusable="false"
      android:layout_height="wrap_content"
      android:layout_marginright="5dp" />

    <imageview
      android:id="@+id/pic_goods"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:scaletype="fitcenter"
      android:src="@drawable/shopping" />

    <linearlayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginleft="10dp"
      android:orientation="vertical" >

      <textview
        android:id="@+id/id_goods"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="短袜男士星期 polo棉袜潮男秋冬款礼盒装"
        android:textcolor="@color/gry_999999"
        android:textsize="@dimen/small_size" />

      <linearlayout
        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="vertical" >

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

            <textview
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="颜色:"
              android:textcolor="@color/gry_999999"
              android:textsize="12sp" />

            <textview
              android:id="@+id/color_goods"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="黑色"
              android:textcolor="@color/gry_999999"
              android:textsize="12sp" />
          </linearlayout>

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

            <textview
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="规格:"
              android:textcolor="@color/gry_999999"
              android:textsize="12sp" />

            <textview
              android:id="@+id/type_goods"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="普通"
              android:textcolor="@color/gry_999999"
              android:textsize="12sp" />
          </linearlayout>

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

            <textview
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="所需积分"
              android:textcolor="@color/theme_color"
              android:textsize="12sp" />

            <textview
              android:id="@+id/integral_goods"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="1000"
              android:layout_marginleft="5dp"
              android:textcolor="@color/theme_color"
              android:textsize="12sp" />
          </linearlayout>
        </linearlayout>

        <linearlayout
          android:layout_width="match_parent"
          android:layout_height="25dp"
          android:layout_gravity="bottom"
          android:layout_marginbottom="5dp"
          android:layout_marginright="5dp"
          android:gravity="right"
          android:orientation="horizontal" >

          <linearlayout
    android:layout_width="80dp"
    android:layout_height="25dp"
    android:layout_gravity="right"
    android:background="@color/white"
    android:orientation="horizontal" >

    <button
      android:id="@+id/minus"
      android:layout_width="25dp"
      android:layout_height="match_parent"
      android:background="@drawable/kuangzi1"
      android:gravity="center"
      android:focusable="false"
      android:text="-"
      android:textcolor="@color/black" >
    </button>

    <textview
      android:id="@+id/number"
      android:layout_width="30dp"
      android:layout_height="match_parent"
      android:background="@drawable/kuangzi1"
      android:gravity="center"
      android:inputtype="number"
      android:text="1"
      android:textcolor="@color/black" >
    </textview>

    <button
      android:id="@+id/plus"
      android:layout_width="25dp"
      android:layout_height="match_parent"
      android:background="@drawable/kuangzi1"
      android:gravity="center"
      android:focusable="false"
      android:text="+"
      android:textcolor="@color/black" >
    </button>
  </linearlayout>
        </linearlayout>
      </linearlayout>
    </linearlayout>
  </linearlayout>

  <view
    android:layout_width="match_parent"
    android:layout_height="0.1dp"
    android:background="@color/divider_color" />

</linearlayout>

实体类:

package com.autoserve.net33.model;


public class test {
  @override
  public string tostring() {
    return "test [id=" + id + ", color=" + color
        + ", type=" + type + ", integral=" + integral + "]";
  }

  public string getid() {
    return id;
  }
  public void setid(string id) {
    this.id = id;
  }
  public string getcolor() {
    return color;
  }
  public void setcolor(string color) {
    this.color = color;
  }
  public string gettype() {
    return type;
  }
  public void settype(string type) {
    this.type = type;
  }
  public string getintegral() {
    return integral;
  }
  public void setintegral(string integral) {
    this.integral = integral;
  }
  private string id;
  private string color;
  private string type;
  private string integral;
  private int num;//商品数量
  private int sumintegral;
  private boolean ischoosed;   //商品是否在购物车中被选中

  public test(string id, string color, string type, string integral) {
    super();
    this.id = id;
    this.color = color;
    this.type = type;
    this.integral = integral;
  }
  public test() {
    super();
  }

  public int getnum() {
    return num;
  }

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

  public int getsumintegral() {
    return sumintegral;
  }

  public void setsumintegral(int sumintegral) {
    this.sumintegral = sumintegral;
  }

  public boolean ischoosed() {
    return ischoosed;
  }

  public void setchoosed(boolean ischoosed) {
    this.ischoosed = ischoosed;
  }  
}

以上就是本文的全部内容,祝大家在新的一年里工作顺利,事事顺心,我们大家共同努力。