burgoyne
burgoyne

Reputation: 163

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...

Upvotes: 0

Views: 36

Answers (2)

Ahmed Abdelaal
Ahmed Abdelaal

Reputation: 159

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

}

Upvotes: 1

DevilsHnd - 退した
DevilsHnd - 退した

Reputation: 9192

To see if a JCheckBox is check-marked you would use .isSelected() not .isChecked(). There is no .isChecked() with a JCheckBox:

if (chkbxUpgrade.isSelected()) {
    cost = 6.99;
}
else {
    cost = 4.99;
}

unless using the method from a different Class. Also, since your cost variable has been declared as a class field it is not required to pass it as a parameter or return it from a method since the variable is class global. Your onCheckboxClicked() method would work just as well with:

public void onCheckboxClicked() {
    if (chkbxUpgrade.isSelected()) {
        cost = 6.99;
    }
    else {
        cost = 4.99;
    }
}

Unless using the onCheckboxClicked() method from another class.

Upvotes: 1

Related Questions