安卓listview实现购物车

安卓listview实现购物车

废话不多说先来看看,效果呀

1.主要功能有上面编辑框可以设置listview的编辑,有删除功能
这里写图片描述
2.点击编辑后,整个界面fragment 进入编辑模式,上面文本变保存,下面文本框变删除,在listview条目中选择要删除的条目,点击删除,即可。
这里写图片描述
3.在checkbox的对应的item中选中可以下下边合计价格统计价格合计
这里写图片描述
4.条目中的商品的数量可以通过按键控制加减数量
这里写图片描述
5.listview中 item的checkbox外面的和全选checkbox可以实现监听同步
这里写图片描述

下面就开始跟着一起去实现吧

先实现界面

  • 先从布局开始说起
    主listview代码
<?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:orientation="vertical"  
    android:background="@color/white"
    >
    <RelativeLayout
            android:background="@color/white"
            android:paddingTop="5.0dip"
            android:paddingBottom="5.0dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
        <ImageView
                android:id="@+id/btn_back_fragment_shopcar"
                android:padding="10.0dip"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10.0dip"
                android:src="@drawable/icon_back_gray"
                android:layout_centerVertical="true"

                android:contentDescription="@null"/>
        <!--  此处购物车需要获取物品数量,后期要动态设置 -->
        <TextView
                android:textSize="20.0sp"
                android:textColor="@color/black"
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/index_shopcar"
                android:layout_centerInParent="true"/>
        <TextView
                android:textSize="20.0sp"
                android:textColor="@color/black"
                android:id="@+id/tv_fragment_shopcar_reset"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/index_reset"
                android:layout_alignParentRight="true"
                android:layout_marginRight="10.0dip"
                android:layout_centerVertical="true"
                />       
    </RelativeLayout>
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        >        
            <!-- 这个就是这个界面的主角购物呀,伙计们 -->
            <ListView 
                android:id="@+id/lv_fragment_shopcar_cart"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                >                                
            </ListView>                                              
    </LinearLayout>
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="55dp"
        android:orientation="horizontal"

        >
        <CheckBox 
            android:id="@+id/total_check_fragment_shopcar"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:text="@string/shopcar_bottom_total_check" 
            android:layout_toRightOf="@id/total_check_fragment_shopcar"
            android:layout_marginLeft="30dp"
            android:gravity="center_vertical"
            android:textSize="18dp"
            android:textColor="#656565"
            android:id="@+id/tv_fragment_shopcar_text02"

            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:text="@string/shopcar_bottom_total_sum" 
            android:layout_alignParentRight="true"
            android:layout_marginRight="160dp"
            android:gravity="center_vertical"
            android:textSize="14dp"
            android:textColor="#999999"
            android:id="@+id/tv_fragment_shopcar_text01"
            />
           <TextView
               android:id="@+id/tv_fragment_shopcar_total_sum"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:text="0" 
            android:layout_alignParentRight="true"
            android:layout_marginRight="118dp"
            android:gravity="center_vertical"
            android:textSize="14dp"
            android:textColor="#00802d"      
            />
           <Button
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:id="@+id/btn_fragment_shopcar_pushsum"
            android:layout_alignParentRight="true"
            android:background="@drawable/tatol"
            android:textSize="14dp"
            android:text="@string/shopcar_bottom_total_sum_btn"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingTop="18dp"
            android:paddingBottom="18dp"
               />          
    </RelativeLayout>    
</LinearLayout>

下面看看条目的item xml布局
注意最外面父容器的descendantFocusability属性为了使条目里面的imageview获得点击的焦点哦
详细可见另一位大牛的讲解关于listview item里面有点击的博客

<?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:orientation="horizontal" 
   android:background="@color/gray_disable"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:descendantFocusability="blocksDescendants"
        android:gravity="center_vertical"
        android:orientation="horizontal" 
        android:id="@+id/shopcar_good_item_ll"
        android:background="@color/gray_disable"
        >
        <CheckBox
            android:id="@+id/shopcar_item_check"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent" 
            android:focusable="false"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            />
        <ImageView
            android:id="@+id/shopcar_item_image"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="@drawable/iamge_ceshi"
            android:gravity="center_vertical" 
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            />
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center_vertical"
            android:orientation="vertical"
            android:layout_marginTop="15dp"          
             >
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >
                <TextView
                    android:id="@+id/shopcar_item_product_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="全国万达"                    
                    android:textSize="14dp" 
                    android:textColor="#333333"/>
              <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal" 
                android:layout_marginTop="10dp"
                >
                <TextView                 
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/shopcar_item_text1"                               
                     android:textSize="14dp" 
                    android:textColor="#333333"
                     />
                  <TextView
                    android:id="@+id/shopcar_item_product_pv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="3600"
                    android:textColor="#00802d"
                    android:textSize="14dp" />
                  <TextView
                    android:id="@+id/shopcar_item_product_price"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="¥45.00"
                    android:textColor="#999999"
                    android:textSize="14dp" 
                    android:layout_marginLeft="5dp"/>                
                     </LinearLayout>
            </LinearLayout>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                 >
                <ImageView
                    android:id="@+id/shopcar_item_btn_sub"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"                                    
                   android:background="@drawable/shopcar_item_sub" />
                <TextView
                    android:id="@+id/shopcar_item_product_count"
                    android:layout_width="45dp"
                    android:layout_height="fill_parent"
                   android:gravity="center"
                android:background="@drawable/shaperpro2"
                    android:text="1"
                    android:textColor="#333333"                 
                    android:textSize="14dp" />
                <ImageView
                    android:id="@+id/shopcar_item_btn_add"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                     android:background="@drawable/shopcar_item_sum" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
  • 看完xml布局,接下来去看看,猪脚,listview的适配器啦
package mxcg.pv.pv.adapter;

import java.util.List;
import android.content.Context;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import mxcg.pv.pv.R;
import mxcg.pv.pv.adapter.my.BeanCart;
import mxcg.pv.pv.cache.ImageLoader;
public class ShopCarAdapter extends BaseAdapter{
    //集合 ,存放ListView的商品实体类数据
         private List<BeanCart> products;
         //上下文
         private Context context;
         //图片加载器
         private ImageLoader imageLoader;   
         //第一步,设置接口,这里方便在外面的activity或者fragment进行回调
         private View.OnClickListener onAddNum;
         private View.OnClickListener onSubNum;
         private View.OnClickListener onCheck;  
          //第二步,设置接口方法
         public void setOnAddNum(View.OnClickListener onAddNum){
              this.onAddNum = onAddNum;
         }    
        public void setOnCheck(View.OnClickListener onCheck){
            this.onCheck = onCheck;
         }
        public void setOnSubNum(View.OnClickListener onSubNum){
            this.onSubNum = onSubNum;
         }
          public ShopCarAdapter(List<BeanCart> products, Context context) {
            this.products = products;
             this.context = context;
             imageLoader=new ImageLoader(context);
          }   
         @Override
         public int getCount() {
             int ret = 0;
             if (products != null) {
                 ret = products.size();
             }
             return ret;
        }
             @Override
         public Object getItem(int i) {
             return products.get(i);
         }

        @Override
         public long getItemId(int i) {
             return i;
        }    
         @Override
         public View getView(int i, View view, ViewGroup viewGroup) {
             View v = null;
            if (view != null) {
                 v = view;
             }else{
                 v = LayoutInflater.from(context).inflate(R.layout.shopcar_good_item,viewGroup,false);
             }   
            ViewHolder holder = (ViewHolder) v.getTag();
             if (holder == null) {
                 holder = new ViewHolder();              
                  holder.item_product_descp = (TextView) v.findViewById(R.id.shopcar_item_product_name);
                  holder.item_product_count = (TextView) v.findViewById(R.id.shopcar_item_product_count);
                  holder.item_product_pv=(TextView) v.findViewById(R.id.shopcar_item_product_pv);                 
                  holder.item_product_price = (TextView) v.findViewById(R.id.shopcar_item_product_price);
                  holder.item_iv_img= (ImageView) v.findViewById(R.id.shopcar_item_image);
                  //第三步,设置接口回调,注意参数不是上下文,它需要ListView所在的Activity或者Fragment处理接口回调方法
                  holder.item_iv_add = (ImageView) v.findViewById(R.id.shopcar_item_btn_add);
                  holder.item_iv_add.setOnClickListener(onAddNum);   
                  holder.item_iv_sub = (ImageView) v.findViewById(R.id.shopcar_item_btn_sub);
                  holder.item_iv_sub.setOnClickListener(onSubNum);
                  holder.item_cb_check=(CheckBox) v.findViewById(R.id.shopcar_item_check);
                  holder.item_cb_check.setOnClickListener(onCheck);
             }   
                holder.item_product_descp.setText(products.get(i).getDesc());
                holder.item_product_count.setText(products.get(i).getCount());
                holder.item_product_pv.setText(products.get(i).getPv());
                String price= '¥'+products.get(i).getPrice();
                holder.item_product_price.setText(price);
                holder.item_product_price.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG); //中划线              
                holder.item_cb_check.setChecked(products.get(i).isChecked());
                //显示图片
                imageLoader.DisplayImage(products.get(i).getImagepath(),holder.item_iv_img);                            
                holder.item_product_count.setText(products.get(i).getCount());                          
             //第四步,设置Tag,用于判断用户当前点击的哪一个列表项的按钮
             holder.item_iv_add.setTag(i);
             holder.item_iv_sub.setTag(i);
             holder.item_cb_check.setTag(i);     
             v.setTag(holder);
              return v;
          }
         private static class ViewHolder{
             //商品名称,数量,总价
            private TextView item_product_descp;
             private TextView item_product_count;
             private TextView item_product_pv;
              private TextView item_product_price;
             //增减商品数量按钮
             private ImageView item_iv_add;
             private ImageView item_iv_sub;          
             //商品的图标
             private ImageView item_iv_img;
             //是否选择
             private CheckBox item_cb_check;     
         }              
     }


适配器也是学习这位博主写的,感谢大牛

下面看看fragment里面的事件处理

package mxcg.pv.pv.fragment;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yolanda.nohttp.Logger;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.Response;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import mxcg.pv.pv.R;
import mxcg.pv.pv.adapter.ShopCarAdapter;
import mxcg.pv.pv.adapter.my.BeanCart;
import mxcg.pv.pv.cache.ImageLoader;
import mxcg.pv.pv.entity.request.RequestShopcarsetBean;
import mxcg.pv.pv.nohttp.CallServer;
import mxcg.pv.pv.nohttp.FastJsonRequest;
import mxcg.pv.pv.nohttp.HttpCallBack;
import mxcg.pv.pv.utils.MyConstants;
import mxcg.pv.pv.utils.Toast;
public class FragmentShopCar extends Fragment implements View.OnClickListener {
    //此列表存放出服务器加载的购物车数据 
    private List<BeanCart> goods;
    //listview本尊
     private ListView lv;
     // 网络图片加载器
     private ImageLoader imageLoad=new ImageLoader(getContext());
     //nohttp,第一次用,感觉不错,棒棒哒
     private FastJsonRequest cartRequest;
     private FastJsonRequest saveRequest;
     //nohttp请标示
     private final int NOHTTP_SHOPCAR=1;
     private final int NOHTTP_SHOPCAR_SAVE=2;
     private ImageView backBtn;
     private TextView tv_sumpv,tv_text01,tv_text02;
     private final int REFRESH=2;
     //条目自定义适配器
     private ShopCarAdapter adapter;
     // 主页的checkbox
     private CheckBox allCheck;
     private TextView tv_setitem;
     private boolean setState=false;
     //checkbox选中的个数
     private int chooseNumber=0;     
     private Button btn_push;
     // 合计积分花费,我们要花多少钱都在这里啦,多少妹子月末总想着这个数字,哇哈哈
     private int totalpv=0; 
/**
 * 观察者模式,监听listview的数据变换,学了这么久的架构,第一次用上观察者模式,幸福哈哈。观察,就是把关,妹子不舒服了就关心下
 */
private DataSetObserver sumObserver = new DataSetObserver() {
/**
 * 当Adapter的notifyDataSetChanged方法执行时被调用,一变化就看是编辑模式还是正常模式,正常的就就计算合计,设置结算选中个数
 */
@Override
public void onChanged() {
super.onChanged();                             
totalPv();// 计算总价
 tv_sumpv.setText(totalpv+"");
 if(!setState){
 btn_push.setText("结算"+"("+totalCheckNumber()+")");
     }              
}

 /**
 * 当Adapter 调用 notifyDataSetInvalidate方法执行时被调用,目前还不用
 */
 @Override
 public void onInvalidated() {
    super.onInvalidated();
    totalPv();// 计算总价
    tv_sumpv.setText(totalpv+"");
    }
 }; 
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    goods=new ArrayList<BeanCart>();    
    View v= inflater.inflate(R.layout.fragment_shopcar, container, false);
    backBtn=(ImageView) v.findViewById(R.id.btn_back_fragment_shopcar);
    backBtn.setOnClickListener(this);
    //购物车显示列表
    lv=(ListView) v.findViewById(R.id.lv_fragment_shopcar_cart);
    tv_sumpv=(TextView) v.findViewById(R.id.tv_fragment_shopcar_total_sum);
    allCheck=(CheckBox) v.findViewById(R.id.total_check_fragment_shopcar);
    allCheck.setOnClickListener(this);
    tv_setitem=(TextView) v.findViewById(R.id.tv_fragment_shopcar_reset);
    tv_setitem.setOnClickListener(this);
    tv_text01=(TextView) v.findViewById(R.id.tv_fragment_shopcar_text01);
    tv_text02=(TextView) v.findViewById(R.id.tv_fragment_shopcar_text02);
    btn_push=(Button) v.findViewById(R.id.btn_fragment_shopcar_pushsum);
    btn_push.setOnClickListener(this);
    return v;
    }
@Override
public void onResume() {    
    super.onResume();
    loadShopcart();
}
/**
 * 这里网络加载购物车数据
 *@author  water
 * QQ376596444
 *2016年5月11日 
 * @version 1.0
 */
private void loadShopcart() {
    SharedPreferences sp = getActivity().getSharedPreferences("userInfo", getActivity().MODE_PRIVATE);
    String appCode=sp.getString("APP_CODE",null);   
    String cartUrl=MyConstants.SHOPCART+appCode;
    Log.i("INFO", cartUrl);
    cartRequest=new FastJsonRequest(cartUrl,RequestMethod.POST);
    CallServer.getInstance().add(getActivity(),cartRequest, callBack,NOHTTP_SHOPCAR, true, false,
            true);  
}
/**
 * 
 * JSON数据网络数据回调监听,用的还是手动解析,也是醉了,懒的要死要死的
 * 
 */
private HttpCallBack<JSONObject> callBack = new HttpCallBack<JSONObject>() {
    @Override
    public void onSucceed(int what, Response<JSONObject> response) {
    //请求成功解析购物车列表
        if(what==NOHTTP_SHOPCAR){
            JSONObject jsonObject = response.get();
            String errmsg = jsonObject.getString("errmsg");
            if(errmsg.equals("00")){
                Logger.i("购物车列表请求成功");
                String data =jsonObject.getString("data");
                JSONArray jsonArray = new JSONArray();
                jsonArray = JSONArray.parseArray(data);
                List<BeanCart> loadbean=new ArrayList<BeanCart>();
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject ja = jsonArray.getJSONObject(i);
                    Logger.i(ja.toString());
                    String num=ja.getString("num");
                    String pkey=ja.getString("pkey");
                    String vendorgoods=ja.getString("vendorgoods");
                    JSONObject vgood=JSONObject.parseObject(vendorgoods);
                    String imagepath = vgood.getString("photo");
                    imagepath = MyConstants.HOST + imagepath;
                    String descp=vgood.getString("name");
                    String pv=vgood.getString("pv");
                    String price=vgood.getString("price");                  
                    BeanCart beancart=new BeanCart(imagepath,descp, pv, price,num,pkey);
                    loadbean.add(beancart) ;                                        
                }
                //清楚原有的列表
                if(goods.size()!=0){

                    goods.removeAll(goods);
                Logger.i("开始清空goods");
                }
                Logger.i(goods.size()+"个啦购物");
                if(loadbean.size()!=0){
                    //有数据就赋值刷新list
                    for(int j=0;j<loadbean.size();j++){
                        goods.add(loadbean.get(j));
                    }
                    Logger.i(goods.size()+"个啦购物");
                }else{
                    //我就不刷新,设置背景为空的购物车                  
                }
                startInitListview();
            }else{
                String data = jsonObject.getString("data");
                 Toast.show(data);
            }           
        }
        if(what==NOHTTP_SHOPCAR_SAVE){
            // 保存请求
            JSONObject jsonObject = response.get();
            String errmsg = jsonObject.getString("errmsg");
            if(errmsg.equals("00")){                
                Toast.show("保存成功");
            }else{
                Toast.show("保存失败");
            }           
        }
    }
    //加载数据完毕,初始listview
    private void startInitListview() {
        adapter=new ShopCarAdapter(goods,getContext());
        //设置Adapter的数据变化观察者,只要Adapter的notifyDataSet被调用,观察者自动调用
         adapter.registerDataSetObserver(sumObserver);
        lv.setAdapter(adapter);
        //好巧妙的设置监听,第一次看别人这么用,我也学学,用用更健康
        adapter.setOnAddNum(listener);
        adapter.setOnSubNum(listener);
        adapter.setOnCheck(listener);
        }
    /**
     * 这里处理我们listview item里面的监听事件
     */
    protected OnClickListener listener=new OnClickListener() {      
        @Override
        public void onClick(View v) {
             Object tag = v.getTag();
             int key=v.getId();
             switch (key) {
             case R.id.shopcar_item_btn_add: //点击添加数量按钮,执行相应的处理
             // 获取 Adapter 中设置的 Tag
             if (tag != null && tag instanceof Integer) { //解决问题:如何知道你点击的按钮是哪一个列表项中的,通过Tag的position
             int position = (Integer) tag;
             //更改集合的数据
             int num =Double.valueOf(goods.get(position).getCount()).intValue() ;
             num++;
             goods.get(position).setCount(num+""); //修改集合中商品数量
             //解决问题:点击某个按钮的时候,如果列表项所需的数据改变了,如何更新UI
             adapter.notifyDataSetChanged();                     
              }
             break;
             case R.id.shopcar_item_btn_sub: //点击减少数量按钮 ,执行相应的处理
                 // 获取 Adapter 中设置的 Tag
                    if (tag != null && tag instanceof Integer) {
                      int position = (Integer) tag;
                      //更改集合的数据
                      int num = Double.valueOf(goods.get(position).getCount()).intValue();
                      if (num>0) {
                        num--;
                        goods.get(position).setCount(num+""); //修改集合中商品数量
                        adapter.notifyDataSetChanged();                    
                      }
                    }
                    break;
             case R.id.shopcar_item_check: //处理选中时间
                    // 获取 Adapter 中设置的 Tag
                    if (tag != null && tag instanceof Integer) {
                      int position = (Integer) tag;
                      //更改集合的数据
                      boolean ischecked=goods.get(position).isChecked();
                      ischecked=!ischecked;
                        goods.get(position).setChecked(ischecked); 
                        if(isTheBoxallCheck()){
                            allCheck.setChecked(true);
                        }else{
                            allCheck.setChecked(false);
                        }
                        adapter.notifyDataSetChanged();                
                      }                 
                    break;
            default:
                break;
            }           
        }
        /**
         * 判断是否全选   
         *@author  water
         * QQ376596444
         *2016年5月11日 
         * @version 1.0
         */
        private boolean isTheBoxallCheck() {
            for(int i=0;i<goods.size();i++){
                if(!goods.get(i).isChecked()){
                    return false;
                };
            }
            return true;
        }
    };
    /*
     *  根据goods计算总价
     */                     
    @Override
    public void onFailed(int what, String url, Object tag, Exception exception, int responseCode,
            long networkMillis) {
        if (what == NOHTTP_SHOPCAR) {
            Toast.show("请求失败");         
    }
        if(what==NOHTTP_SHOPCAR_SAVE){
            // 保存请求     
                Toast.show("保存连接失败");                   
        }
    }
};
/**
 * 计算当前的选中个数
 *@author  water
 * QQ376596444
 *2016年5月11日 
 * @version 1.0
 */
public int totalCheckNumber(){
    int cnumber=0;
    for(int i=0;i<goods.size();i++){
        if(goods.get(i).isChecked()){
            cnumber++;
        }
    }   
    return cnumber;
}
/**
 * 计算当前状态的pv总数
 *@author  water
 * QQ376596444
 *2016年5月11日 
 * @version 1.0
 */
public int totalPv(){
    totalpv=0;
    for(int i=0;i<goods.size();i++){
        int count =Double.valueOf(goods.get(i).getCount()).intValue();
        int itempv =Double.valueOf(goods.get(i).getPv()).intValue();
        boolean check=goods.get(i).isChecked();
        int choose=0;
        if(check){
            choose=1;
        }       
        int item=count*choose*itempv;
        totalpv+=item;      
    }
    return totalpv;
}
//处理这个fargment的点击事件
@Override
public void onClick(View v) {   
    int key=v.getId();
    switch (key) {
    case R.id.btn_back_fragment_shopcar:
        Toast.show(" 点击了回退");       
        break;
    case R.id.total_check_fragment_shopcar:
        //  处理全选的逻辑             
        if(allCheck.isChecked()){
        checkAllItem();
        }else{
            uncheckAllItem();
        }               
        break;
    case R.id.tv_fragment_shopcar_reset:
        //处理编辑的逻辑
        if(!setState){
        setState=true;
        //出现删除条目
        beginsetItemGone();
        }else{
            //恢复源条目
            saveResetItem();
            reSetItemStay();
            setState=false;
        }
        break;      
    case R.id.btn_fragment_shopcar_pushsum:
        //处理提交的任务分在state在删除状态和提交状态
        if(!setState){
             //处理提交的业务
            Toast.show("提交购物车数据");
        }else{
            //处理删除的业务
            deleteChooseItem();
            //需要提交修改后的数据
            Toast.show("提交删除过的购物车数据");          
        }               
        break;
    default:
        break;
    }   
}
/**
 * 保存提交修改的购物车列表
 *@author  water
 * QQ376596444
 *2016年5月11日 
 * @version 1.0
 */
private void saveResetItem() {
    List<RequestShopcarsetBean> beans=new ArrayList<RequestShopcarsetBean>();
    //这里写提交列表的到服务器  
    for(int i=0;i<goods.size();i++){
        BeanCart beanCart=new BeanCart();
        beanCart=goods.get(i);
        String pkey=beanCart.getPkey();
        String num=beanCart.getCount(); 
        RequestShopcarsetBean sbean=new RequestShopcarsetBean(pkey, num);               
        beans.add(sbean);       
    }
    String jsonString = JSON.toJSONString(beans);  
    Log.i("json", jsonString);
    cartRequest=new FastJsonRequest(MyConstants.SHOPCARTDSAVE,RequestMethod.POST);
    cartRequest.add("list",jsonString);
    CallServer.getInstance().add(getActivity(),cartRequest, callBack,NOHTTP_SHOPCAR_SAVE, true, false,
            true);  
}
/**
 * 选中删除条目
 *@author  water
 * QQ376596444
 *2016年5月11日 
 * @version 1.0
 */
private void deleteChooseItem() {
    int j=goods.size();
    for(int i=j-1;i>=0;i--){
        if(goods.get(i).isChecked()){
            //选中移除
            goods.remove(i);            
        }       
    }
    adapter.notifyDataSetChanged(); 
}
/**
 * 正常状态
 *@author  water
 * QQ376596444
 *2016年5月11日 
 * @version 1.0
 */
private void reSetItemStay() {
    tv_text01.setVisibility(View.VISIBLE);
    tv_text02.setVisibility(View.VISIBLE);
    tv_sumpv.setVisibility(View.VISIBLE);
    btn_push.setText("结算"+"("+totalCheckNumber()+")");
    tv_setitem.setText("编辑");
}
/**
 * 编辑状态
 *@author  water
 * QQ376596444
 *2016年5月11日 
 * @version 1.0
 */
private void beginsetItemGone() {
    tv_text01.setVisibility(View.GONE);
    tv_text02.setVisibility(View.GONE);
    tv_sumpv.setVisibility(View.GONE);
    btn_push.setText("删除");
    tv_setitem.setText("保存");   
}
//设置列表不全选,并刷新列表
private void uncheckAllItem() {
    for(int i=0;i<goods.size();i++){
        goods.get(i).setChecked(false);
    }
    adapter.notifyDataSetChanged(); 
}
/*
 * 设置列表全选,并刷新列表
 */
public void checkAllItem(){

    for(int i=0;i<goods.size();i++){
        goods.get(i).setChecked(true);
    }
    adapter.notifyDataSetChanged(); 
}
/**
 * 记得在destroy移除观察者订阅
 *@author  water
 * QQ376596444
 *2016年5月11日 
 * @version 1.0
 */
@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    adapter.unregisterDataSetObserver(sumObserver);
}
}

标注标注里面用的MyConstents. 的基本就是url了,自己到网上找点图片就可以了。
再推荐一篇博客

观察者时间处理

感谢大牛的分享,本人菜鸟一枚,有错误的地方请指出。

  • 5
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值