注意:不是很完美

//--------------------主布局文件---------------------------------

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

     <TextView android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:text="已选中个数"
        android:id="@+id/tv_num"
        android:gravity="center"/>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:orientation="horizontal"
        >
        <CheckBox android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="fill_parent"
            android:text="全选"
            android:gravity="center"
            android:id="@+id/cb_quanxuan"/>
        <CheckBox android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="fill_parent"
            android:text="反选"
            android:gravity="center"
            android:id="@+id/cb_fanxuan"/>
    </LinearLayout>
    <ListView android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/lv"></ListView>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:orientation="horizontal"
        >
        <TextView android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="2"
            android:text="总价:"
            android:id="@+id/tv_zongjai"
            android:gravity="center"/>
        <Button android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="支付"
            android:id="@+id/bt_zifu"
            android:gravity="center"/>
    </LinearLayout>

</LinearLayout>

//------------------bean包-----------------------------------

package com.example.wodequanxuan;

public class Goods {
    private String title;
    private String money;
    private boolean flag;
    public Goods(String title, String money, boolean flag) {
        super();
        this.title = title;
        this.money = money;
        this.flag = flag;
    }
    public Goods() {
        super();
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getMoney() {
        return money;
    }
    public void setMoney(String money) {
        this.money = money;
    }
    public boolean isFlag() {
        return flag;
    }
    public void setFlag(boolean flag) {
        this.flag = flag;
    }
    @Override
    public String toString() {
        return "Goods [title=" + title + ", money=" + money + ", flag=" + flag
                + "]";
    }
    
    

}

//--------------------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="horizontal" >
    <CheckBox android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:id="@+id/cb_checkbox"
        android:gravity="center"/>
    <TextView android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/tv_title"/>
    <TextView android:layout_width="100dp"
        android:layout_height="80dp"
        android:id="@+id/tv_money"
        android:gravity="center"/>
    

</LinearLayout>

//-------------------适配器------------------------------

package com.example.wodequanxuan;

import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter{
    private List<Goods> goods;
    private Context context;
    
     private static HashMap<Integer, Boolean> isSelected;
        private onCheckListener listener;
        private CheckBox check;
    

    public MyAdapter(List<Goods> goods, Context context) {
        super();
        this.goods = goods;
        this.context = context;
        
        
         isSelected = new HashMap<Integer, Boolean>();
            for (int i = 0; i < goods.size(); i++) {
               getIsSelected().put(i, false);
            }  
    }

    

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return goods.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return goods.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        Goods goodss=goods.get(position);
        if (convertView==null) {
            convertView=View.inflate(context, R.layout.list_item, null);
            holder=new ViewHolder();
            holder.title=(TextView) convertView.findViewById(R.id.tv_title);
            holder.money=(TextView) convertView.findViewById(R.id.tv_money);
            holder.flag=(CheckBox) convertView.findViewById(R.id.cb_checkbox);
            convertView.setTag(holder);
        }
        holder=(ViewHolder) convertView.getTag();
        holder.title.setText(goodss.getTitle());
        holder.money.setText(goodss.getMoney()+"");
        holder.flag.setChecked(goodss.isFlag());
        
         // 根据isSelected来设置checkbox的选中状况
        holder.flag.setChecked(getIsSelected().get(position));
        holder.flag.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 自动生成的方法存根
                if (isSelected.get(position)) {
                    isSelected.put(position, false);
                    setIsSelected(isSelected);
                } else {
                    isSelected.put(position, true);
                    setIsSelected(isSelected);
                }
               listener.onCheck(isSelected);
            }

            
            
        });
        
        return convertView;
    }
    
    static class ViewHolder{
        public TextView title;
        public TextView money;
        public CheckBox flag;
    }
    
    
      public static HashMap<Integer, Boolean> getIsSelected() {
            return isSelected;
        }

        public static void setIsSelected(HashMap<Integer, Boolean> isSelected) {
            MyAdapter.isSelected = isSelected;
        }

        public void setListener(onCheckListener listener) {
            this.listener = listener;
        }

        public interface onCheckListener {
            void onCheck(HashMap<Integer, Boolean> map);
          }

}

//-----------------------Activity 中------------------------------------------------

package com.example.wodequanxuan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.wodequanxuan.MyAdapter.onCheckListener;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity implements onCheckListener {
    private String urlPath="http://172.17.29.120/localuser/loupengfei/kaoshi/shoppingcar.json";
    private List<Goods> goods=new ArrayList<Goods>();
    private TextView tv_num;
    private TextView tv_zongjai;
    private CheckBox cb_fanxuan;
    private CheckBox cb_quanxuan;
    
     private int checkNum = 0; // 记录选中的条目数量
     private float total = 0.00f;
    
    private Handler handler=new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0:
                String text=(String) msg.obj;
                tojson(text);
                break;

            default:
                break;
            }
        }

        

        
    };
    private ListView lv;
    private MyAdapter adapter;
  
    
    
    private void tojson(String text) {
        try {
            JSONObject obj=new JSONObject(text);
            JSONArray data=obj.getJSONArray("data");
            for (int i = 0; i < data.length(); i++) {
                JSONObject json=data.getJSONObject(i);
                String title=json.getString("title");
                String money=json.getString("money");
                Goods goodss=new Goods(title, money,false);
                goods.add(goodss);
            }
            
            adapter = new MyAdapter(goods, this);
            lv.setAdapter(adapter);
            
            adapter.setListener(this);
            
            
            
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        
        
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
      
        
        //找到控件
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_zongjai = (TextView) findViewById(R.id.tv_zongjai);
        cb_fanxuan = (CheckBox) findViewById(R.id.cb_fanxuan);
        cb_quanxuan = (CheckBox) findViewById(R.id.cb_quanxuan);
        lv = (ListView) findViewById(R.id.lv);
        //获得数据
        huodeshuju();
        
        //cb_fanxuan.setOnClickListener(this);
        //cb_quanxuan.setOnClickListener(this);
        
        //反选
        cb_fanxuan.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                
                  checkNum=0;
                //不为全选时,也就是有选中的,有没选中的
                // 遍历list的长度,设为未选
                for (int i = 0; i < goods.size(); i++) {
                       //获得当条目的选中状态                 
                    Boolean n=adapter.getIsSelected().get(i);
                    //如果选中,设为不选中
                    if (n) {                       
                            adapter.getIsSelected().put(i, false);
                            //获得选中条目的布尔值
                            Boolean a=adapter.getIsSelected().get(i);
                            //
                            if (a) {
                                total+=Float.valueOf(goods.get(i).getMoney());
                                Log.i("总价111:", total+"");
                                checkNum++;// 数量减1
                            }                                                                           
                    }else{                        
                        adapter.getIsSelected().put(i, true);
                        Boolean a=adapter.getIsSelected().get(i);
                        if (a) {                                                        
                            total+=Float.valueOf(goods.get(i).getMoney());
                            Log.i("总价222:", total+"");
                            checkNum++;// 数量减1
                        }                                                                                                    
                    }
                  
                    
                }
               
             // 刷新listview和TextView的显示
                dataChanged(total);
                //设置全选为不选中状态
                cb_quanxuan.setChecked(false);
            }
        });
        
        //全选
        cb_quanxuan.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //当全选框变为全选时,
                if (isChecked) {
                    // 当不是全选时,设置为全选
                    total = 0.00f;               
                        // 遍历list的长度,设为已选
                        checkNum = goods.size();
                        for (int i = 0; i < goods.size(); i++) {
                            adapter.getIsSelected().put(i, true);
                            total += Float.valueOf(goods.get(i).getMoney()) ;
                        }
                    
                    // 刷新listview和TextView的显示
                    dataChanged(total);
                    
                }else{
                    // 遍历list的长度,设为未选
                    for (int i = 0; i < goods.size(); i++) {
                        adapter.getIsSelected().put(i, false);
                        checkNum=0;// 数量减1
                        total = 0.00f;
                    }
                 // 刷新listview和TextView的显示
                    dataChanged(total);
                   
                }
                
                //把反选设置为不选中
                cb_fanxuan.setChecked(false);
                
            }
        });

}

    private void huodeshuju() {
        new Thread(){
            public void run() {
                try {
                    URL url=new URL(urlPath);
                    HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
                    urlConnection.setConnectTimeout(5000);
                    urlConnection.setReadTimeout(5000);
                    urlConnection.setRequestMethod("GET");
                    
                    int code=urlConnection.getResponseCode();
                    if (code==200) {
                        InputStream inputStream=urlConnection.getInputStream();
                        BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
                        String liner;
                        StringBuffer buffer=new StringBuffer();
                        while ((liner=reader.readLine())!=null) {
                            buffer.append(liner);
                            
                        }
                        String str=buffer.toString();
                        Log.i("shuju:", str);
                        Message message=new Message();
                        message.what=0;
                        message.obj=str;
                        handler.sendMessage(message);
                        }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            };
        }.start();
        
    }

   

    private void dataChanged(float total2) {
           DecimalFormat decimalFormat = new DecimalFormat();// 构造方法的字符格式这里如果小数不足2位,会以0补足.
            String price_num = decimalFormat.format(total);// format 返回的是字符串
            String str = "合计" + "¥" + price_num + " ";
            // 通知listView刷新
            adapter.notifyDataSetChanged();
            // 用TextView显示       总价、选中数量
            tv_zongjai.setText(str);
            tv_num.setText("已选中:"+checkNum);
        
    }

    @Override
    public void onCheck(HashMap<Integer, Boolean> map) {
           // TODO 自动生成的方法存根
        total = 0.00f;
        checkNum = 0;
        for (int i = 0; i < map.size(); i++) {
            if (map.get(i)) {
                total += Float.valueOf(goods.get(i).getMoney());
                checkNum++;
            }
        }
        //更新显示数据
        dataChanged(total);
        
    }

    
    
}

购物车CheckBox全选、反选的更多相关文章

  1. 表单javascript checkbox全选 反选 全不选

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...

  2. 关于Winform下DataGridView中实现checkbox全选反选、同步列表项的处理

    近期接手一个winform 项目,虽然之前有.net 的经验,但是对一些控件的用法还不是很熟悉. 这段时间将会记录一些在工作中遇到的坎坷以及对应的解决办法,写出来与大家分享并希望大神提出更好解决方法来 ...

  3. jquery、js操作checkbox全选反选

    全选反选checkbox在实际应用中比较常见,本文有个不错的示例,大家可以参考下 操作checkbox,全选反选//全选 function checkAll() { $('input[name=&qu ...

  4. jquery checkbox 全选反选代码只能执行一遍,第二次就失败

    遇到问题背景: 在写到购物车的全选交互的时候,商品选中的状态只有在第一次的时候可以,第二次就无法选中:(代码如下) $(".chooseall").click(function() ...

  5. checkbox 全选反选实现全代码

    //跳转到指定action function validateForm(url){ if($("#form").form('validate')){ var x=document. ...

  6. C# WinForm中实现CheckBox全选反选功能

    今天一群里有人问到这个功能,其实应该挺简单,但提问题的人问题的出发点并没有描述清楚.因此,一个简简单单的需求,就引起了群内热烈的讨论.下面看看这个功能如何去实现,先上效果: 下面直接上代码,请不要在意 ...

  7. 表单Checkbox全选反选全不选

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. Jquery学习笔记(4)--checkbox全选反选

    可能有浏览器兼容性,注意html里的checked是一个属性,存在就默认选中. <!DOCTYPE html> <html lang="en"> <h ...

  9. jQuery实现checkbox全选反选及删除等操作

    1.list.html 说明:用checkbox数组Check[]存放每一行的ID值 <div id="con"> <table width="100% ...

随机推荐

  1. Java 算法

    1.简单的冒泡排序 //冒泡算法一共两种 // -----冒泡算法(1) int a[]={23,69,4,58,1,20}; for (int i = 0; i < a.length-1; i ...

  2. Openjudge-计算概论(A)-分数求和

    描述: 输入n个分数并对他们求和,并用最简形式表示.所谓最简形式是指:分子分母的最大公约数为1:若最终结果的分母为1,则直接用整数表示. 如:5/6.10/3均是最简形式,而3/6需要化简为1/2, ...

  3. ios 将彩色照片转化成黑白等几种类型

    -(UIImage *)changeColoursImageTograyScaleImage:(UIImage *)anImage type:(int)type { CGImageRef imageR ...

  4. window.showModalDialog()的简单用法

    //创建一个显示html内容的模态对话框: vReturnValue = window.showModalDialog(sURL [, vArguments] [,sFeatures]) //创建一个 ...

  5. Python 学习笔记5

    Life is like a box of chocolate. 今天继续学习Python数据结构. http://www.pythondoc.com/pythontutorial3/datastru ...

  6. NGUI等比缩放

    /// <summary> /// UI 等比缩放 /// </summary> static private void AdaptiveUI() { ; ; UIRoot u ...

  7. 将json文件转换为字符串

    //从给定位置读取Json文件    public   String readJson(String path){        //从给定位置获取文件        File file = new ...

  8. jquery ui sortable 实现table,row的拖动。(Make Table Rows Sortable Using jQuery UI Sortable)

    // Return a helper with preserved width of cells var fixHelper = function(e, ui) { //console.log(ui) ...

  9. .net 2.0 后台多线程

    System.Threading.Thread thread1 = new System.Threading.Thread(delegate() { Web.BLL.banpaiconfig.Vide ...

  10. HTTP SOAP Request

    public string SoapRequest(string url, string message, string type, Encoding encoding) { string resul ...