无法使用复选框选择填充字符串

Unable to populate string with checkbox selection

我有一个似乎无法弄清楚的简单问题。我希望有人能提供帮助,但在研究了复选框之后,我仍然无法解决这个问题。

这是我的代码:

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

如果复选框未选中,我的 textview 是否应该填充 4.99,如果选中,是否应该填充 6.99?我不明白为什么它没有填充...

要查看 JCheckBox 是否已选中,您可以使用 .isSelected() 而不是 .isChecked()。没有 .isChecked() 和 JCheckBox:

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

除非使用来自不同 Class 的方法。 此外,由于您的 cost 变量已声明为 class 字段,因此不需要将其作为参数传递或 return 从方法中传递,因为变量是 class 全球。您的 onCheckboxClicked() 方法同样适用于:

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

除非使用来自另一个 class 的 onCheckboxClicked() 方法。

xml 看起来像:

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

然后将您的方法更改为:

public void onCheckboxClicked(View view) {
    // Is the view now checked?
    boolean checked = ((CheckBox) view).isChecked();

   if (checked)
   { 
       cost = 6.99;
   }
   else
   {
      cost =4.99;
   }

}