选中CheckBox时Android Studio App崩溃

时间:2016-09-13 12:09:52

标签: android android-studio

当我选中复选框时,应用程序崩溃了,否则程序会运行

XML:

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/whippedCreamTopping"
            android:onClick="onCheckboxClicked"
            />    

Java:

    //This method is called when the order button is clicked.
    public void submitOrder(View view) {
        CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whippedCreamTopping);
        boolean hasWhippedCream = whippedCreamCheckBox.isChecked();    
        int price = calculatePrice();
        String priceMessage = createOrderSummary(price, hasWhippedCream);
        displayMessage(priceMessage);   

    }


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

    //Calculates the price of the order.
    private int calculatePrice() {
        return quantity * price;
    }

    //Add in a summary
        private String createOrderSummary(int price, boolean addWCream) {
        double priceTotal = calculatePrice();  
        String myName = "JJ Jobs";
        String priceString = "Name: " + myName;
        priceString += "\nAdd Whipped Cream?" + addWCream;
        priceString += "\nQuantity: " + quantity + "\nTotal: $" + priceTotal;
        priceString += "\nThank you";
        return priceString;
    } //end of createOrderSummary

我试过How to check if android checkbox is checked within its onClick method (declared in XML)? 但我没有得到代码(复选框工作)

1 个答案:

答案 0 :(得分:1)

我在XML代码中发现了问题:

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/whippedCreamTopping"

        android:onClick="onCheckboxClicked"  *I removed this line of code 
                                             *then it worked
        />  

感谢您的所有帮助