Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> andriod編程 仿購物車功能實現

andriod編程 仿購物車功能實現

編輯:關於Android編程

購物車

最近寫了一個商城APP中常用功能“購物車”

購物車效果圖如下:
購物車效果圖

購物車功能需求如下:
購物車要求

下面是購物車主activity“MainActivity”代碼:

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Response;
import shop.hsy.com.shopcar.adapter.ShopAdapter;
import shop.hsy.com.shopcar.entity.ResultModel;
import shop.hsy.com.shopcar.entity.Shopping;
import shop.hsy.com.shopcar.net.ShopCarNet;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView shop_list;
    private ShopAdapter shopAdapter;
    private TextView prices;
    private CheckBox all_checks;
    private TextView settlement;
    private TextView delete_text;
    private Response>> modelResponse;//接口請求回來的數據
    private List shoppingList = new ArrayList<>();//重新整合後的數據
    private ProgressDialog progressDialog;
    private int a=0;//此字段非常重要,用來解決全選與單選沖突
    private int b=1;//此字段非常重要,用來解決字段a與全選沖突

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("······");
        initview();
    }

    private void initview(){
        shop_list = (ListView) findViewById(R.id.shop_list);
        shopAdapter = new ShopAdapter(MainActivity.this);
        shop_list.setAdapter(shopAdapter);

        all_checks = (CheckBox) findViewById(R.id.all_checks);//全選
        prices = (TextView) findViewById(R.id.prices);//價格
        settlement = (TextView) findViewById(R.id.settlement);//結算
        delete_text = (TextView) findViewById(R.id.delete_text);//刪除
        settlement.setOnClickListener(this);
        delete_text.setOnClickListener(this);
        getShopData(22+"");
        AllChecks();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.settlement: //結算
                Settlement();
                break;
            case R.id.delete_text: //刪除
                AllDelete();
                break;
        }
    }

    /**
     * 數據接口請求
     * @param mid
     */
    private void getShopData(final String mid){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    modelResponse = ShopCarNet.getShop(mid).execute();
                    Message message = mhandler.obtainMessage();
                    message.what = 0;
                    message.sendToTarget();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private Handler mhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    if(modelResponse!=null){
                        if(modelResponse.body()!=null){
                            if(modelResponse.body().getData()!=null
                        &&modelResponse.body().getData().size()>0){
                                for (Shopping shop:modelResponse.body().getData()) {
                                    shop.setChecks(false);//給商品添加為選中狀態
                                    shoppingList.add(shop);
                                }
                                shopAdapter.addItem(shoppingList);
                                shopAdapter.notifyDataSetChanged();
                            }
                        }
                    }else{
                        Log.e("mainactivity","沒有數據");
                    }
                    break;
            }
        }
    };

    /**
     * 全選check監聽
     */
    public void AllChecks(){
        all_checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                progressDialog.show();
                if(b==0){
                    a=0;b=1;
                }
                if(a==0) {//解決單選與全選沖突
                    if (isChecked) {//true:全選被選中,false:全選取消
                        double AllPrice = 0;
                        for (Shopping shop : shoppingList) {
                            shop.setChecks(true);//改變商品選中狀態
                            AllPrice = AllPrice + Double.valueOf(shop.p_price) * shop.p_number;//計算商品總價
                        }
                        prices.setText("¥" + AllPrice);//顯示總價
                    } else {
                        b=0;
                        for (Shopping shop : shoppingList) {
                            shop.setChecks(false);//改變商品未選中狀態
                        }
                        prices.setText("¥0.0");//價格改為0
                    }
                    shopAdapter.clear();
                    shopAdapter.addItem(shoppingList);//添加改編後的數據到list的Adapter
                    shopAdapter.notifyDataSetChanged();//刷新列表
                }
                a=0;
                if (progressDialog != null) progressDialog.cancel();
            }
        });
    }

    /**
     * 選中,加減方法
     * @param checks 是否被選中
     * @param count 被選中的商品id
     * @param number 被選中商品的數量
     */
    public void UpView(boolean checks, int count,int number){
        progressDialog.show();
        double AllPrice = 0;
        int size = 0 ;//用來計數,判斷數據是否被全部選中
        for (Shopping shop:shoppingList) {
            if(shop.p_id == count){//查找被選中商品id
                shop.setChecks(checks);//改變商品集合shoppingList中的選中狀態
                shop.p_number = number;//同時修改商品數量
            }

            if(shop.isChecks()){//判斷商品是否被選中,如被選中計算價格
                size++;
                AllPrice =AllPrice + Double.valueOf(shop.p_price) * shop.p_number;//得到被選中商品的總價格
            }
        }
        shopAdapter.clear();
        shopAdapter.addItem(shoppingList);
        shopAdapter.notifyDataSetChanged();
        prices.setText("¥"+AllPrice);
        if(size == shoppingList.size()){
            all_checks.setChecked(true);//是全部被選中,改變全選check狀態為選中
        }else{
            a = 1;//a=1表示all_checks監聽中方法不執行
            if(!all_checks.isChecked()) a=0;//all_checks未被選中給a賦值0讓all_checks的監聽中的方法繼續執行
            all_checks.setChecked(false);//不是,繼續維持未選中狀態
        }
        if (progressDialog != null) progressDialog.cancel();
    }

    /**
     * 結算方法
     */
    public void Settlement(){
        List settlement_list = new ArrayList<>();
        final List new_list = new ArrayList<>();
        for (Shopping shop:shoppingList) {
            if(shop.isChecks()){
                settlement_list.add(shop.p_id);//取出被選中商品id加入新的list准備掉接口完成結算
            }else{
                new_list.add(shop);//剩余商品形成新的購物車列表等待顯示
            }
        }
        if(settlement_list.size()==0){
            Toast.makeText(MainActivity.this,"請選中至少一個商品後在結算",Toast.LENGTH_SHORT).show();
            return;
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
        dialog.setTitle("提示").setMessage("總共"+settlement_list.size()+"個商品,共"+prices.getText().toString()+"元,是否要結算?");
        dialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //在這裡調結算接口把delete_list傳給後台
                shoppingList = new_list;
                shopAdapter.clear();
                shopAdapter.addItem(shoppingList);
                shopAdapter.notifyDataSetChanged();
                prices.setText("¥0.0");
                dialog.cancel();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).create().show();
    }

    /**
     * 刪除方法
     * 該方法類似結算方法
     */
    public void AllDelete(){
        List delete_list = new ArrayList<>();
        final List new_list = new ArrayList<>();
        for (Shopping shop:shoppingList) {
            if(shop.isChecks()){
                delete_list.add(shop.p_id);
            }else{
                new_list.add(shop);
            }
        }
        if(delete_list.size()==0){
            Toast.makeText(MainActivity.this,"請選中至少一個商品後在刪除",Toast.LENGTH_SHORT).show();
            return;
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
        dialog.setTitle("提示").setMessage("確定要刪除這"+delete_list.size()+"個商品?");
        dialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //在這裡調刪除接口把delete_list傳給後台
                shoppingList = new_list;
                shopAdapter.clear();
                shopAdapter.addItem(shoppingList);
                shopAdapter.notifyDataSetChanged();
                prices.setText("¥0.0");
                dialog.cancel();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).create().show();
    }

}

MainActivity的布局文件很簡單:




    

        
    

    

        
    

    

        


        

        

        

        

    

購物車Adapter代碼“ShopAdapter”,由於我繼承一個BaseAtapter,所以這個Adapter我只需要處理getView方法:

import android.content.Context;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.ImageLoader;
import shop.hsy.com.shopcar.MainActivity;
import shop.hsy.com.shopcar.MyApplication;
import shop.hsy.com.shopcar.R;
import shop.hsy.com.shopcar.entity.Shopping;

/**
 * Created by hsy on 2016/11/10.
 */

public class ShopAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private Context context;
    private MainActivity mainActivity;

    public ShopAdapter(Context context) {
        this.context = context;
        mainActivity = (MainActivity)context;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.shop_item, parent, false);
            holder.checks = (CheckBox) convertView.findViewById(R.id.checks);//選擇框
            holder.p_img1 = (ImageView) convertView.findViewById(R.id.p_img1);//商品縮略圖
            holder.p_name = (TextView) convertView.findViewById(R.id.p_name);//名稱
            holder.p_price = (TextView) convertView.findViewById(R.id.p_price);//價格
            holder.p_mprice = (TextView) convertView.findViewById(R.id.p_mprice);//過時價格
            holder.p_discount = (TextView) convertView.findViewById(R.id.p_discount);//折扣
            holder.p_news = (TextView) convertView.findViewById(R.id.p_news);//成色
            holder.p_stock = (TextView) convertView.findViewById(R.id.p_stock);//庫存
            holder.p_number = (TextView) convertView.findViewById(R.id.p_number);//數量
            holder.minus = (ImageView) convertView.findViewById(R.id.minus);//減
            holder.add = (ImageView) convertView.findViewById(R.id.add);//加
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final Shopping shopping = (Shopping) getItem(position);
        if (!TextUtils.isEmpty(shopping.p_img1)) {
            ImageLoader.getInstance().displayImage(shopping.p_img1, holder.p_img1, MyApplication.option);
        }else {
            holder.p_img1.setImageResource(R.mipmap.ic_launcher);
        }
        holder.p_name.setText(shopping.p_name);
        holder.p_price.setText(shopping.p_price);
        holder.p_mprice.setText(shopping.p_mprice);
        holder.p_discount.setText(shopping.p_discount);
        holder.p_news.setText(shopping.p_news);
        holder.p_number.setText(shopping.p_number+"");
        holder.p_stock.setText(shopping.p_stock);
        holder.checks.setChecked(shopping.isChecks());
        holder.p_mprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        //全選監聽
        holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mainActivity.UpView(isChecked, shopping.p_id, shopping.p_number);
            }
        });
        //數量減
        holder.minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int minus = 0;
                if(shopping.p_number>1) {
                    minus = shopping.p_number-1;
                    mainActivity.UpView(shopping.isChecks(), shopping.p_id, minus);
                }else{
                    Toast.makeText(context,"數量不能再少了",Toast.LENGTH_SHORT).show();
                }
            }
        });
        //數量加
        holder.add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mainActivity.UpView(shopping.isChecks(),shopping.p_id,(shopping.p_number+1));
            }
        });
        return convertView;
    }

    private class ViewHolder {
        private CheckBox checks;
        private ImageView p_img1;
        private TextView p_name;
        private TextView p_price;
        private TextView p_mprice;
        private TextView p_discount;
        private TextView p_news;
        private TextView p_stock;
        private TextView p_number;
        private ImageView minus;
        private ImageView add;
    }
}

Adapter布局文件:




    

    

    

        

        

            

            

            

            

        

        

            

            

                
                

                
            
        
    

至此,購物車功能就實現了,這裡最主要的就是MainActivity中的UpView方法,其次就是CheckBox的監聽(setOnCheckedChangeListener); 注意 :在MainActivity中我用了a和b兩個字段來解決Adapter中的CheckBox監聽和Activity中的CheckBox監聽沖突問題。

源碼下載

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved