Search code examples
androidandroid-studiomobileswitch-statement

Quantity Button with RadioGroup To Calculate Subtotal Price


Hello I have been struggling to figure out how to get the subtotal with my quantity increment and decrement buttons for subtotal.

What I want is after the customers chooses a type the price will show on the bottom. Then if they would like multiple orders they can press the + button and the price will change as well depending if they increase or decrease. Here is the Code

MainActivity

public class expresso_item1 extends AppCompatActivity  {

private Spinner spinner;

RadioGroup radioGroup;
RadioButton radioButton;
TextView textView;


TextView value;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_expresso_item1);

    value = (TextView) findViewById(R.id.quantity1);
    radioGroup = findViewById(R.id.radioGroup);
    textView = findViewById(R.id.total1);



}

public void RButton (View v){
    int radioID = radioGroup.getCheckedRadioButtonId();
    switch(radioID){
        case R.id.type1:
            textView.setText("$"+"5");
            break;
        case R.id.type2:
            textView.setText("$"+"10");
            break;
        case R.id.type3:
            textView.setText("$"+"12");
            break;
    }


}

public void plus (View v){
    count++;
    value.setText("" + count);
}

public void minus (View v){
    if (count <= 0 ) count = 0;
    else count--;
    value.setText("" + count);
}

}

Currently only shows the type price the customer wants. Any help is appreciated!

Here is a pic of the Design Layout: Design


Solution

  • Try this instead

    Initialize another global variable to get the current price below the count

    int count = 0
    int currentPrice = 0
    

    Then in the RButton() set the new value for the currentPrice

    public void RButton (View v){
        int radioID = radioGroup.getCheckedRadioButtonId();
        switch(radioID){
            case R.id.type1:
                textView.setText("$"+"5");
                currentPrice = 5
                break;
            case R.id.type2:
                textView.setText("$"+"10");
                currentPrice = 10
                break;
            case R.id.type3:
                textView.setText("$"+"12");
                currentPrice = 15
                break;
        }
    
    
    }
    

    Then in the plus and minus function

    public void plus (View v){
        count++;
        value.setText("" + String.valueOf(count * currentPrice));
    }
    
    public void minus (View v){
        if (count <= 0 ) count = 0;
        else count--;
        value.setText("" + String.valueOf(count * currentPrice));
    }
    }