【问题标题】:Cart item Count increment/decrement & add to cart购物车项目计数增加/减少并添加到购物车
【发布时间】:2016-08-02 13:19:32
【问题描述】:

大家好,我正在使用自定义列表视图从服务器获取数据并显示在列表视图中。我能够获取数据并将其显示在列表视图中,但我不知道在列表项中实现按钮的单击事件。有两个按钮可以增加和减少数量。我的 clicklistener 正在工作,但它的工作方式不正确。当我单击增加或减少产品时,应将其添加到购物车。请帮我纠正这个问题。我确实在 中搜索了太多帖子,但无法理解...

这是我的适配器类代码:

public class ProductsAdapter extends BaseAdapter {
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();

private Context context;
private ArrayList<HashMap<String, String>> postItems;
public SharedPreferences settings;
public final String PREFS_NAME = "Products";

DisplayImageOptions options;
ImageLoaderConfiguration imgconfig;

private static int _counter = 0;
private String _stringVal;

public ProductsAdapter(Context context, ArrayList<HashMap<String, String>> arraylist){
    this.context = context;

    File cacheDir = StorageUtils.getCacheDirectory(context);
    options = new DisplayImageOptions.Builder()
    .showImageOnLoading(R.drawable.loading)
    .showImageForEmptyUri(R.drawable.loading)
    .showImageOnFail(R.drawable.loading)
    .cacheInMemory(true)
    .cacheOnDisk(true)
    .considerExifParams(true)
    .displayer(new SimpleBitmapDisplayer())
    .imageScaleType(ImageScaleType.EXACTLY)
    .build();

    imgconfig = new ImageLoaderConfiguration.Builder(context)
    .build();
    ImageLoader.getInstance().init(imgconfig);

    postItems = arraylist;
    settings = context.getSharedPreferences(PREFS_NAME, 0);     

}

@Override
public int getCount() {
    return postItems.size();
}
@Override
public Object getItem(int position) {       
    return postItems.get(position);
}

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
            context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.row_products, null);   
        }
        final HashMap<String, String> map = postItems.get(position);

        ImageView imgProduct = (ImageView)convertView.findViewById(R.id.proimage);
        ImageLoader.getInstance().displayImage(ConstValue.PRO_IMAGE_BIG_PATH+map.get("image"), imgProduct, options, animateFirstListener);

        TextView txtTitle = (TextView)convertView.findViewById(R.id.proTitle);
        txtTitle.setText(map.get("title"));

        TextView txtPrice = (TextView)convertView.findViewById(R.id.txtprice);
        txtPrice.setText(map.get("price"));

        TextView textDiscount = (TextView)convertView.findViewById(R.id.textDiscount);
        textDiscount.setVisibility(View.GONE);

        TextView txtDiscountFlag = (TextView)convertView.findViewById(R.id.textDiscountFlag);
        txtDiscountFlag.setVisibility(View.GONE);

        TextView textCurrency = (TextView)convertView.findViewById(R.id.textCurrency);
        textCurrency.setText(map.get("currency"));

        final TextView value = (TextView)convertView.findViewById(R.id.textView3);

        Button txtminus = (Button) convertView.findViewById(R.id.minus);

        txtminus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.d("src", "Decreasing value...");
            _counter--;
            _stringVal = Integer.toString(_counter);
            value.setText(_stringVal);

            if (_counter < 0)
            {
                value.setText("0");
            }

        }
        });

        Button txtplus  = (Button) convertView.findViewById(R.id.plus);
        txtplus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("src", "Increasing value...");
            _counter++;
            _stringVal = Integer.toString(_counter);
            value.setText(_stringVal);
        }
        });


        if(!map.get("discount").equalsIgnoreCase("") && !map.get("discount").equalsIgnoreCase("0")){
            Double discount = Double.parseDouble(map.get("discount"));
            Double price = Double.parseDouble(map.get("price"));
            Double discount_amount =  discount * price / 100;

            Double effected_price = price - discount_amount ; 
            //txtPrice.setBackgroundResource(R.drawable.strike_trough);
            txtPrice.setPaintFlags(txtPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            textDiscount.setVisibility(View.VISIBLE);
            textDiscount.setText(effected_price.toString());

            txtDiscountFlag.setVisibility(View.VISIBLE);
            txtDiscountFlag.setText(discount+"% off");
        }

        TextView txtUnit = (TextView)convertView.findViewById(R.id.txtunit);
        txtUnit.setText(map.get("gmqty"));

        TextView txtgm = (TextView)convertView.findViewById(R.id.txtgm);
        txtgm.setText(map.get("unit"));

        int a = Integer.parseInt(map.get("total_qty_stock").toString());
        int b = Integer.parseInt(map.get("consume_qty_stock").toString());

        int result = a - b;

        TextView txtstock = (TextView)convertView.findViewById(R.id.stock);
        txtstock.setText(String.valueOf(result)+" "+map.get("type")+" In Stock");
        //txtstock.setText(map.get("stock")+" "+map.get("type")+" In Stock");


    return convertView;
}

}

这是我的 ProductActivity 代码

公共类 ProductsActivity 扩展 ActionBarActivity {

public SharedPreferences settings;
public ConnectionDetector cd;
static ArrayList<HashMap<String, String>> products_array;
ProductsAdapter adapter;
ListView products_listview;
DisplayImageOptions options;
ImageLoaderConfiguration imgconfig;
ProgressDialog dialog;

TextView txtcount;
Button btn;

private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
HashMap<String, String>  catMap;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
    settings = getSharedPreferences(ConstValue.MAIN_PREF, 0);
    cd = new ConnectionDetector(getApplicationContext());

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_products);

/*  ActionBar mActionBar = getActionBar();
    mActionBar.setDisplayShowHomeEnabled(true);
    mActionBar.setDisplayShowTitleEnabled(true);
    LayoutInflater mInflater = LayoutInflater.from(this);

    View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
    TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text);
    mTitleTextView.setText("My Own Title");

    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true); */

    settings = getSharedPreferences(ConstValue.MAIN_PREF, 0);
    cd=new ConnectionDetector(this);

    File cacheDir = StorageUtils.getCacheDirectory(this);
    options = new DisplayImageOptions.Builder()
    .showImageOnLoading(R.drawable.loading)
    .showImageForEmptyUri(R.drawable.loading)
    .showImageOnFail(R.drawable.loading)
    .cacheInMemory(true)
    .cacheOnDisk(true)
    .considerExifParams(true)
    .displayer(new SimpleBitmapDisplayer())
    .imageScaleType(ImageScaleType.NONE)
    .build();

    imgconfig = new ImageLoaderConfiguration.Builder(this)
    .build();
    ImageLoader.getInstance().init(imgconfig);

    ArrayList<HashMap<String,String>> categoryArray = new ArrayList<HashMap<String,String>>();
    try {
        categoryArray = (ArrayList<HashMap<String,String>>) ObjectSerializer.deserialize(settings.getString("categoryname", ObjectSerializer.serialize(new ArrayList<HashMap<String,String>>())));
    }catch (IOException e) {
            e.printStackTrace();
    }

    catMap = new HashMap<String, String>();
    catMap = categoryArray.get(getIntent().getExtras().getInt("position"));

    products_array = new ArrayList<HashMap<String,String>>();
    try {
        products_array = (ArrayList<HashMap<String,String>>) ObjectSerializer.deserialize(settings.getString("products_"+catMap.get("id"), ObjectSerializer.serialize(new ArrayList<HashMap<String,String>>())));
    }catch (IOException e) {
            e.printStackTrace();
    }

    products_listview = (ListView)findViewById(R.id.listView1);
    adapter = new ProductsAdapter(getApplicationContext(), products_array);
    products_listview.setAdapter(adapter);

    TextView txtTitle = (TextView)findViewById(R.id.catname);
    txtTitle.setText(catMap.get("name"));

    txtcount = (TextView)findViewById(R.id.textcount);

    btn = (Button) findViewById(R.id.button);

    products_listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, final int position,
                                long id) {
            // TODO Auto-generated method stub

            try {

                settings.edit().putString("selected_product", ObjectSerializer.serialize(products_array.get(position))).commit();



            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Intent intent = new Intent(ProductsActivity.this, ProductdetailActivity.class);
            intent.putExtra("position", position);
            startActivity(intent);

        }
    });


    new loadProductsTask().execute(true);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}




public class loadProductsTask extends AsyncTask<Boolean, Void, ArrayList<HashMap<String, String>>> {

    JSONParser jParser;
    JSONObject json;
    String count;
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        // TODO Auto-generated method stub
        if (result!=null) {
            //adapter.notifyDataSetChanged();
        }   
        try {
            settings.edit().putString("products_"+catMap.get("id"), ObjectSerializer.serialize(products_array)).commit();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        txtcount.setText(count);
        adapter.notifyDataSetChanged();
        super.onPostExecute(result);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

    @Override
    protected void onCancelled(ArrayList<HashMap<String, String>> result) {
        // TODO Auto-generated method stub
        super.onCancelled(result);
    }


    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            Boolean... params) {
        // TODO Auto-generated method stub

        try {
            jParser = new JSONParser();

            if(cd.isConnectingToInternet())
            {
                String urlstring = ConstValue.JSON_PRODUCTS+"&id="+catMap.get("id");
                json = jParser.getJSONFromUrl(urlstring);
                count = json.getString("count");
                if (json.has("data")) {
                    if(json.get("data") instanceof JSONArray){
                        JSONArray jsonDrList = json.getJSONArray("data");
                        products_array.clear();
                        for (int i = 0; i < jsonDrList.length(); i++) {
                            JSONObject obj = jsonDrList.getJSONObject(i);
                            put_object(obj);
                        }
                    }else if(json.get("data") instanceof JSONObject){
                        put_object(json.getJSONObject("data"));
                    }
                }
            }else
            {
                Toast.makeText(ProductsActivity.this, "Please connect mobile with working Internet", Toast.LENGTH_LONG).show();
            }

            jParser = null;
            json = null;

            } catch (Exception e) {
                // TODO: handle exception

                return null;
            }
        return null;
    }

    public void put_object(JSONObject obj){
        HashMap<String, String> map = new HashMap<String, String>();


        try {
        map.put("id", obj.getString("id"));
        map.put("title", obj.getString("title"));
        map.put("slug", obj.getString("slug"));
        map.put("description", obj.getString("description"));       
        map.put("image", obj.getString("image"));

        map.put("price", obj.getString("price"));
        map.put("currency", obj.getString("currency"));
        map.put("discount", obj.getString("discount"));
        map.put("cod", obj.getString("cod"));       
        map.put("emi", obj.getString("emi"));       
        map.put("status", obj.getString("status"));     

        map.put("gmqty", obj.getString("gmqty"));       
        map.put("unit", obj.getString("unit"));     
        map.put("deliverycharge", obj.getString("deliverycharge"));     
        map.put("tax", obj.getString("tax"));       
        map.put("category_id", obj.getString("category_id"));

        map.put("on_date", obj.getString("on_date"));

        map.put("stock", obj.getString("stock"));
        map.put("type", obj.getString("type"));
        map.put("total_qty_stock", obj.getString("total_qty_stock"));
        map.put("consume_qty_stock", obj.getString("consume_qty_stock"));

        products_array.add(map);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

}

【问题讨论】:

  • 有什么问题..?
  • 当价值增加或减少时,产品应添加到购物车

标签: android listview


【解决方案1】:

这一行……​​

private static int _counter = 0;

因此,当您单击列表中的 任何 项时,您只跟踪适配器中所有项的一个数字,而不是每个 单个 项。

我建议你定义一些面向对象的设计来获得CartProduct 类。这将允许您以比 Hashmap 到 ListView 更简洁的方式跟踪列表中的项目及其详细信息和数量。

一旦您有了 Product 类,我建议您研究如何实现 ArrayAdapter&lt;Product&gt;

【讨论】:

    【解决方案2】:

    您可以使用接口覆盖方法在活动类中实现接口,并将接口作为参数传递给适配器构造函数。让我们创建一个名为 increment 的接口。

    public interface Increment {
      void addCount(boolean ADD_FLAG);
    }
    

    在您的活动中实现这一点。

    Class CartActivity implements Increment {
    
    @Override
    public void addCount(boolean ADD_FLAG) {
    if (ADD_FLAG) {
    //If true increment..
    } else{
    //If false decrement..
    }
    }
    

    将接口作为参数传递给适配器构造函数,如下所示。

    Increment increment = null;
    
    public ProductsAdapter(Context context, ArrayList<HashMap<String, String>> arraylist, Increment increment) {
      this.increment = increment;
    }
    

    最后在你的点击监听器中。

    //Add this line to increment..
    increment.addCount(true);
    
    //Add this line to decrement..
        increment.addCount(false);
    

    希望这会有所帮助:)

    【讨论】:

      【解决方案3】:

      创建一个接口,例如;

      interface QuantityChangeListener {
          void onQuantityChanged(HashMap<String, String> map);
      }
      

      在您创建上述适配器的地方实现此接口。

      ProductsAdapter adapter = new ProductAdapter(this, "your list",
          new QuantityChangeListener() {
               @Override
               public void onQuantityChanged(HashMap<String, String> map) {
                    // add item to cart
               }
           }
      );
      

      将此接口传递给ProductsAdapter类的构造函数。

      private QuantityChangeListener listener;
      public ProductsAdapter(Context context, ArrayList<HashMap<String, String>> arraylist, QuantityChangeListener listener){
          this.listener = listener;
          // do other stuff
      }
      
      txtplus.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              Log.d("src", "Increasing value...");
              _counter++;
              _stringVal = Integer.toString(_counter);
              value.setText(_stringVal);
              listener.onQuantityChanged(map);
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-01
        • 1970-01-01
        • 2021-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多