lundi 1 octobre 2018

Android update sum of value on each action made

I am doing an application where my textview updates itself immediately based on the checked checkbox and radio button. I have 3 hashmaps to store the values of each items:

    hashMap.put("chkCheese", 2.50);
    hashMap.put("chkPep", 3.50);
    hashMap.put("chkChick", 2.00);
    hashMap.put("chkBeef", 4.00);
    hashMap.put("chkBlackOlives", 2.00);
    hashMap.put("chkPine", 1.00);
    hashMap.put("chkMushroom", 1.00);

And this is my function to show items checked on change for my checkbox:

    private void checkEnoughAndMakeDisabled (CheckBox checkBoxes []) {
    int count = 0;
    for (CheckBox cb:checkBoxes) {
        cb.setEnabled(true);
        if (cb.isChecked()) {
            count++;
            toppingsSelection.add(cb);

        }
    }

    String text="";
    for (CheckBox items: toppingsSelection) {
        text = text + items.getText().toString() + ", ";
    }
    toppings.setText(text);

    if (count >= 5) {
        for (CheckBox cb:checkBoxes) {
            if (!cb.isChecked()) {
                cb.setEnabled(false);
            }
        }
    }
    toppingsSelection.clear();
}

Calling my function in onCreate():

        //Display TOPPINGS text on each action made
    final CompoundButton.OnCheckedChangeListener chgListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            checkEnoughAndMakeDisabled(checkBox);
        }
    };

    for (CheckBox tmpCheckBox: checkBox) {

        tmpCheckBox.setOnCheckedChangeListener(chgListener);
    }

So far i can only show the name of items checked. I tried to do the similar stuff for my TextView priceSum to show the total sum but it doesnt work. I also tried putting the calculation and hashmap tag retrieval inside the checkEnoughAndMakeDisabled function, it crashes. How do you think is the best approach of getting the hashmap's value and do the calculation? My attemp:

       //Display PRICE text on each action made
    price.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            double cal=0.0;
            for (int y=0;y<checkBox.length;y++) {
                if (checkBox[y].isChecked()) {
                    toppingsSelection.add(checkBox[y]);
                }
            }
            for (CheckBox tmpTopping:toppingsSelection) {
                double toppingPriceSum = hashMap.get(tmpTopping.getTag());
                cal = cal + toppingPriceSum;
                String s = "RM " + toppingPriceSum;
                price.setText(s);
            }
            return false;
        }
    });




Aucun commentaire:

Enregistrer un commentaire