将复选框状态从 XML 传递到 Java

Passing a checkbox state from XML to Java

我是 android 开发的新手,我正在尝试使用 findViewById 方法传递复选框状态,但应用程序崩溃了:

这里是 xml 代码:

<CheckBox
        android:id="@+id/toppings_checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16sp"
        android:layout_marginTop="8sp"
        android:layout_marginBottom="16sp"
        android:text="Whipped Cream"
        android:textColor="#FFFFFF"
        android:textSize="20sp"
        android:paddingLeft="16dp"
        android:buttonTint="#FFFFFF"
        />

这是 java 对 link 此复选框的声明 java:

public class MainActivity extends AppCompatActivity {
CheckBox hasWhippedCream = (CheckBox) findViewById(R.id.toppings_checkbox);
boolean checked = hasWhippedCream.isChecked();
int quantity = 0;
int pricePerCup = 5;
int toppingPrice = 0;

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

/**
 * This method is called when the + button is clicked
 */
public void Increment(View view) {
    quantity = quantity + 1;
    displayQuantity(quantity);
}

/**
 * This method is called when the - button is clicked
 */
public void Decrement(View view) {
    quantity = quantity - 1;
    if (quantity < 1) {
        quantity = 1;
    }
    displayQuantity(quantity);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    displayMessage(createOrderSummary(calculatePrice()));
}

/**
 * Calculates the price of the order.
 */
private int calculatePrice() {

    if (checked = true) {
        toppingPrice = 2;
    } else {
        toppingPrice = 0;
    }
    return quantity * (pricePerCup + toppingPrice);
}

/**
 * This method displays summary of the given order.
 *
 * @param total is the total price of the order.
 *              * @return text summary
 */

private String createOrderSummary(int total) {

    String summary = "Name: Captain Samir\n";
    summary += "Add whipped cream? " + checked + "\n";
    summary += "Quantity: " + quantity + " Cups\n";
    summary += "Total: $" + total + "\n";
    summary += "Thank You!";
    return summary;
}

/**
 * This method displays the given quantity value on the screen.
 */
private void displayQuantity(int value) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText("" + value);
}

/**
 * This method displays the given text on the screen.
 */
private void displayMessage(String message) {
    TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
    orderSummaryTextView.setText(message);
}
}

然后我通过程序使用变量checked。知道为什么应用程序一旦启动就会崩溃吗?

试试这个:

public class MainActivity extends AppCompatActivity {
    CheckBox hasWhippedCream;
    boolean checked;
    int quantity = 0;
    int pricePerCup = 5;
    int toppingPrice = 0;

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

        hasWhippedCream = (CheckBox) findViewById(R.id.toppings_checkbox);
        hasWhippedCream.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checked = isChecked;
            }
        });
        checked = hasWhippedCream.isChecked();
    }

   // rest is the same
}

问题出在您的 Java 代码上。这是你犯的两个错误:

  • You were supposed to put your executable code inside your onCreate(), not outside of it.

  • You can only monitor for changes on your checkbox by calling onCheckedChangedListener() on it.

查看以下代码进行更正:

    public class MainActivity extends AppCompatActivity {


    boolean checked;


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

     CheckBox hasWhippedCream = (CheckBox) findViewById(R.id.toppings_checkbox);
     hasWhippedCream.setOnCheckedChangeListener(new OnCheckedChangeListener() {
           @Override
             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             checked = isChecked;
               }
                });


        int quantity = 0;
        int pricePerCup = 5;
        int toppingPrice = 0;

      }

     //Every other part of your code is correct ;-)

      }

希望对您有所帮助.. 编码愉快!!