Search code examples
javaandroidtextviewandroid-checkbox

Unable to populate string with checkbox selection


I have a simple question that I can't seem to figure out. I'm hoping someone can help, but after researching checkboxes, I still cannot solve this.

Here is my code:

CheckBox chkbxUpgrade;
TextView txtViewResult;
Double cost;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtViewResult = (TextView)findViewById(R.id.textViewResult);
    chkbxUpgrade = (CheckBox)findViewById(R.id.checkBoxUpgrade);

    onCheckboxClicked(cost);
}

public double onCheckboxClicked(Double cost) {
    if (chkbxUpgrade.isChecked()) {
        cost = 6.99;
    }
    else {
        cost = 4.99;
    }
    return cost;
}

public void onClickOrder(View view) {
    Toast.makeText(this, "Order Successful!", Toast.LENGTH_LONG).show();
    txtViewResult.setText("Price: $" + cost);
}

Shouldn't my textview be populated with 4.99 if the checkbox is not checked, or 6.99 if it is checked? I cannot figure out why it is not populating...


Solution

  • xml sould look like :

    <CheckBox android:id="@+id/your check box id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text"
            android:onClick="onCheckboxClicked"/>
    

    Then change your method to be:

    public void onCheckboxClicked(View view) {
        // Is the view now checked?
        boolean checked = ((CheckBox) view).isChecked();
    
       if (checked)
       { 
           cost = 6.99;
       }
       else
       {
          cost =4.99;
       }
    
    }