Android中購物車的全選、反選、問題和計算價格


此Demo主要解決的是購物車中的全選,反選計算價格和選中的條目個數的問題,當選中幾條時,點擊反選,會把當先選中的變為不選中,把不選中的變為選中。點擊全選會全部選中,再次點擊時,變為全部不選中

//-----------一下為main的布局-----------------------

<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"
        >
        <Button android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="fill_parent"
            android:text="全選"
            android:gravity="center"
            android:id="@+id/bt_quanxuan"/>
        <Button android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="fill_parent"
            android:text="反選"
            android:gravity="center"
            android:id="@+id/bt_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>

 

//-----------------一下為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" >
    
<LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
            
    <CheckBox android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/cb_checkbox"/>
    <TextView android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/tv_title"
        android:textSize="20sp"/>
    <TextView android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:id="@+id/tv_money"
        android:gravity="center"/>
    </LinearLayout>
</LinearLayout>

 

 

//------------------一下為bean包中封裝的數據對象-----創建了一個News類-----------------------

package com.bwie.test;

public class News {
    private String title;
    private String money;
    private boolean flag;
    public News(String title, String money, boolean flag) {
        super();
        this.title = title;
        this.money = money;
        this.flag = flag;
    }
    public News() {
        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 "News [title=" + title + ", money=" + money + ", flag=" + flag
                + "]";
    }
    

}

 

//---------------一下是自定義的適配器-------MyAdapter-------------------------

package com.bwie.test;

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<News> news;
    private Context context;
    
    private static HashMap<Integer, Boolean> isSelected;
    private onCheckListener listener;
    private CheckBox check;
    
    
    public MyAdapter(List<News> news, Context context) {
        super();
        this.news = news;
        this.context = context;
        
        isSelected = new HashMap<Integer, Boolean>();
        for (int i = 0; i < news.size(); i++) {
           getIsSelected().put(i, false);
        }            
        
    }

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

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return news.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;
        News newss=news.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(newss.getTitle());
        holder.money.setText(newss.getMoney());
        holder.flag.setChecked(newss.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);
      }
    
    
}

 

//--------------------------------------

//========================以下是MainActivity==========================================

package com.bwie.test;

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.bwie.test.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.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity implements onCheckListener, OnClickListener {
    private String urlPath="http://172.17.29.120/localuser/loupengfei/kaoshi/shoppingcar.json";
    private List<News> news=new ArrayList<News>();
        
    private ArrayList<Shopbean> list;
    private int checkNum = 0; // 記錄選中的條目數量
     private float total = 0.00f;
    
    private Button bt_fanxuan;
    private Button bt_quanxuan;
    
    private MyAdapter adapter;
    private TextView tv_num;
    private TextView tv_zongjai;
    private ListView lv;
    private SharedPreferences sp;
    
    
    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 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");
                News newss=new News(title, money, false);
                news.add(newss);
                
            }
            //設置適配器
            adapter = new MyAdapter(news, 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);
        //創建SharedPreferences
        sp = getSharedPreferences("kk", Context.MODE_PRIVATE);
        
        //找到控件
        bt_fanxuan = (Button) findViewById(R.id.bt_fanxuan);
        bt_quanxuan = (Button) findViewById(R.id.bt_quanxuan);
        lv = (ListView) findViewById(R.id.lv);
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_zongjai = (TextView) findViewById(R.id.tv_zongjai);
              
        //獲得數據      
        huodeshuju();       
        //設置監聽
        bt_fanxuan.setOnClickListener(this);
        bt_quanxuan.setOnClickListener(this);
    }

//------------------------------------
    //獲得網絡數據
    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");
                    urlConnection.connect();
                    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();
        
    }
    

    
    
 

    @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(news.get(i).getMoney());
                checkNum++;
            }
        }
        //更新顯示數據
        dataChanged(total);
        
    }

    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 onClick(View v) {
        switch (v.getId()) {
        //全選
        case R.id.bt_quanxuan:
            //去SharedPreferences中獲得是否為全選狀態,true為全選狀態,false為不是全選狀態
            boolean kk=sp.getBoolean("kk", false);
            //為全選時,遍歷設置為全不選
            if (kk) {
                // 遍歷list的長度,設為未選
                for (int i = 0; i < news.size(); i++) {
                    adapter.getIsSelected().put(i, false);
                    checkNum=0;// 數量減1
                    total = 0.00f;
                }
             // 刷新listview和TextView的顯示
                dataChanged(total);
                //保存狀態為全不選
                Editor editor=sp.edit();
                editor.putBoolean("kk", false);
                editor.commit();
            }else{
                // 當不是全選時,設置為全選
                total = 0.00f;               
                    // 遍歷list的長度,設為已選
                    checkNum = news.size();
                    for (int i = 0; i < news.size(); i++) {
                        adapter.getIsSelected().put(i, true);
                        total += Float.valueOf(news.get(i).getMoney()) ;
                    }
                
                // 刷新listview和TextView的顯示
                dataChanged(total);
                //保存全選狀態
                Editor editor=sp.edit();
                editor.putBoolean("kk", true);
                editor.commit();
            }
            
            break;
            //反選
        case R.id.bt_fanxuan:
            checkNum=0;
            //獲得全選狀態
            boolean kkk=sp.getBoolean("kk", false);
            total=0;
            //為全選時,設置為全不選
            if (kkk) {
                // 遍歷list的長度,設為未選
                for (int i = 0; i < news.size(); i++) {
                    adapter.getIsSelected().put(i, false);
                    checkNum=0;// 數量減1
                    total = 0.00f;
                }
             // 刷新listview和TextView的顯示
                dataChanged(total);
                Editor editor=sp.edit();
                editor.putBoolean("kk", false);
                editor.commit();
            }else{
                //不為全選時,也就是有選中的,有沒選中的
                // 遍歷list的長度,設為未選
                for (int i = 0; i < news.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(news.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(news.get(i).getMoney());
                            Log.i("總價222:", total+"");
                            checkNum++;// 數量減1
                        }                                                                                                    
                    }
                  
                    
                }
               
             // 刷新listview和TextView的顯示
                dataChanged(total);
                
            }
            break;

        default:
            break;
        }
        
    }


    
    
}

//==============以上是MainActivity==================完了,趕快試試吧============


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM