2016-08-02 175 views
0

嗨大家好,我正在使用自定义列表视图从服务器获取数据并显示在列表视图中..我能够获取数据并在列表视图中显示,但我不知道实现listitem内按钮的点击事件。有两个按钮来减少和减少数量。我的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; 
} 

} 

result

这里我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(); 
     } 
    } 
} 

}

+1

是什么问题..? – Andolasoft

+0

当数值增加或减少时,应将产品添加到购物车 – Omkar

回答

0

这条线......

private static int _counter = 0; 

所以,当你点击列表中的任意项目,您跟踪只有一个号码用于在适配器的所有项目,而不是每个个人项目。

我建议你定义一些面向对象的设计来获得CartProduct类。这将允许您跟踪列表中的项目,并将它们的详细信息和数量以比Hashmap更清晰的方式放入ListView中。

一旦你有一个产品类,我建议你看看如何实现ArrayAdapter<Product>

0

可以实现与接口重写方法您的活动类接口,并通过接口作为参数传递给适配器构造函数。让我们创建一个名为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); 

希望这有助于:)

0

创建诸如界面;

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 class。

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); 
    } 
});