如何在自定义操作栏上显示总数量?

时间:2015-06-02 08:23:42

标签: java android

如何在自定义操作栏上显示数量总数?

我有一个活动类,其中包括自定义列表视图(名称,数量,加号按钮,减号按钮等)和自定义操作栏。如何在自定义操作栏上显示计数(数量)?< / p>

提前致谢。

活动类

package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;

import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.adapter.CartAdapter;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CartItem;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.Product;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.Product2;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

public class DetaisRESTActivity extends Activity implements CartAdapter.OnUpdateTotal {
    String messagevaluename,valueid,valueid1,valuename,pos;
    public String countString=null;
    String nameofsubmenu;
    public int count=0;
    public  String message=null;
    public  String message1=null;
    JSONObject jsonobject;
    JSONArray jsonarray;
    // Declare Variables
    String rastaurantname1212;
    String success;
    String subtotal1;
    String disCupnPrice1;
    CartAdapter cart;
    String resid1;
    ListView   listview;


    public TextView   mTitleTextView;
    public   ImageButton imageButton;

    ProgressDialog mProgressDialog;
    ArrayList<CartItem> arraylist;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detais_rest);
        ActionBar actionBar = getActionBar();

        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
        LayoutInflater mInflater = LayoutInflater.from(this);

        View mCustomView = mInflater.inflate(R.layout.titlebar, null);
        mTitleTextView = (TextView) mCustomView.findViewById(R.id.txtTotalProducts);



        mTitleTextView.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Refresh Clicked!",
                        Toast.LENGTH_LONG).show();

                Intent i = new Intent(DetaisRESTActivity.this, TotalPriceActivity.class);
                i.putExtra("count", pos);
                i.putExtra("submenu", message);
                i.putExtra("ruppees", message1);
                i.putExtra("messagevaluename", messagevaluename);
                i.putExtra("id", nameofsubmenu);
                startActivity(i);
            }
        });

        actionBar.setCustomView(mCustomView);
        actionBar.setDisplayShowCustomEnabled(true);
          // Locate the TextViews in singleitemview.xml
       TextView txtrestaurantname = (TextView) findViewById(R.id.rastaurantnamesingledetails);
       TextView txtrestaurantcuisine = (TextView) findViewById(R.id.rastaurantcuisinesingledetails);
        // Locate the ImageView in singleitemview.xml
       ImageView imgflag = (ImageView) findViewById(R.id.flagdetails);
       // Set results to the TextViews
        txtrestaurantname.setText(getIntent().getExtras().getString("rastaurantname11"));
        txtrestaurantcuisine.setText(getIntent().getExtras().getString("rastaurantcuisine11"));
        rastaurantname1212=getIntent().getExtras().getString("rastaurantname11");
        resid1=getIntent().getExtras().getString("resid11");
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.clas

        Intent intent = getIntent();
        // get the extra value
        valuename = intent.getStringExtra("restaurantmenuname");
        valueid = intent.getStringExtra("restaurantmenunameid");
        valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
Log.i("valueid",""+valueid);
        Log.i("valueid1",""+valueid1);

        new DownloadJSON().execute();


    }


    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<String,Integer,JSONObject> {

        @Override

        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
            // Set progressdialog title

            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
            Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
        }

        @Override
        protected JSONObject doInBackground(String... params) {
            // Create an array


            // Retrieve JSON Objects from the given URL address

            //  jsonobject = JSONfunctions.getJSONfromURL(");
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(
                        "http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                String response = EntityUtils.toString(httpEntity);
                return new JSONObject(response);

            } catch (Exception e) {

            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject args) {
            // Locate the listview in listview_main.xml
            super.onPostExecute(args);
            try {


                JSONArray jsonarray = args.getJSONArray("RestaurantMenItems");
                Log.i("1234", "" + jsonarray);

                arraylist = new ArrayList<CartItem>();
                for (int i = 0; i < jsonarray.length(); i++) {

                    JSONObject jsonObject = jsonarray.getJSONObject(i);
                    CartItem c=new CartItem(jsonObject.getInt("id"),jsonObject.getString("RestaurantPizzaItemName"),jsonObject.getInt("RestaurantPizzaItemPrice"));
                    arraylist.add(c);

                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            listview = (ListView) findViewById(R.id.listViewSINGLE);

               cart=new CartAdapter(arraylist,DetaisRESTActivity.this,DetaisRESTActivity.this);

            listview.setAdapter(cart);
            getTotalProducts(arraylist);
            // Close the progressdialog

            mProgressDialog.dismiss();




        }
    }


    public int getTotalProducts(ArrayList<CartItem> arrProducts){
          int total=0;
         Log.i("arrProducts",""+arrProducts.size());
        for (int i = 0; i <arrProducts.size(); i++) {
               total+=arrProducts.get(i).getQuantity();


        }
        Log.i("total2",""+total);
        return total;

    }

    @Override
    public void execute(ArrayList<CartItem> arrs) {
        mTitleTextView.setText(getTotalProducts(arrs) + "");
       // CartItem ii=new CartItem(1,"",1);


    }


}

适配器类

package com.firstchoicefood.phpexpertgroup.firstchoicefoodin.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CartItem;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.R;
public class CartAdapter extends BaseAdapter {
    private LayoutInflater inflater;
    private ArrayList<CartItem> arrs;
    private OnUpdateTotal onUpdateTotal;

    public CartAdapter(ArrayList<CartItem> arrs, Context context,
            OnUpdateTotal updateTotal) {
        this.arrs = arrs;
        inflater = LayoutInflater.from(context);
        onUpdateTotal = updateTotal;
    }

    @Override
    public int getCount() {
        return arrs.size();
    }

    @Override
    public CartItem getItem(int position) {
        return arrs.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View v, ViewGroup parent) {
        if (v == null)
            v = inflater.inflate(R.layout.item_cart, null);
        TextView txtName, txtPrice, txtCatagory;
        final EditText edtQuantity;
        Button btnPlus, btnMinus;
        btnPlus = (Button) v.findViewById(R.id.btnPlus);
        btnMinus = (Button) v.findViewById(R.id.btnMinus);
        txtName = (TextView) v.findViewById(R.id.txtName);
        txtPrice = (TextView) v.findViewById(R.id.txtPrice);
        txtCatagory = (TextView) v.findViewById(R.id.txtCatagoryID);
        edtQuantity = (EditText) v.findViewById(R.id.edtQuantity);
        txtName.setText(arrs.get(position).getName());
        txtPrice.setText(arrs.get(position).getPrice() + "");
        txtCatagory.setText(arrs.get(position).getCatogoryID());
        edtQuantity.setText(arrs.get(position).getQuantity() + "");
        edtQuantity.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    arrs.get(position).setQuantity(
                            Integer.parseInt(s.toString()));
                  //  onUpdateTotal.execute(arrs);
                } catch (Exception ee) {

                }
            }
        });
        btnPlus.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                int current = arrs.get(position).getQuantity();

                Log.i("position",""+position);
                Log.i("current",""+current);


                edtQuantity.setText(++current+"");
            }
        });
        btnMinus.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                int current = arrs.get(position).getQuantity();
                edtQuantity.setText(--current+"");
            }
        });
        return v;
    }

    public interface OnUpdateTotal {
        public void execute(ArrayList<CartItem> arrs);
    }


}

模型java类

package com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean;

public class CartItem {
    private int id;
    private String name;
    private float price;
    private int quantity;
    private String catogoryID;

    public CartItem(int id, String name, float price, int quantity,
            String catogoryID) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
        this.catogoryID = catogoryID;
    }
    public CartItem(int id, String name, float price, int quantity) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;

    }
    public CartItem(int id, String name, float price) {
        this.id = id;
        this.name = name;
        this.price = price;


    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
    public String getCatogoryID() {
        return catogoryID;
    }
    public void setCatogoryID(String catogoryID) {
        this.catogoryID = catogoryID;
    }

}

0 个答案:

没有答案