2016-03-02 90 views
0

enter image description here的CheckBox Android Studio中

我有這樣的代碼,這在我的節目我使用複選框。如果複選框被選中,它必須執行if語句中的語句,但即使未選中複選框,我的程序也會執行所有「if語句」。

public void onClickMakeTransactionButton(){ 

     chkAirtime = (CheckBox) findViewById(R.id.chkAirtime); 
     chkElectricity = (CheckBox) findViewById(R.id.chkElectricity); 
     chkWater = (CheckBox) findViewById(R.id.chkWater); 
     chkTransfer = (CheckBox) findViewById(R.id.chkTransfers); 
     chkWithdrawal = (CheckBox) findViewById(R.id.chkWithdrawal); 
     chkPayDstv = (CheckBox) findViewById(R.id.chkPayDstv); 

     final TextView savingsBalance = (TextView) findViewById(R.id.txtSavingsBalance); 
     savingsBalance.setText("Your Balance is: " + balance); 

     btnMakeTransaction = (Button) findViewById(R.id.btnMakeTransaction); 

     btnMakeTransaction.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       StringBuffer result = new StringBuffer(); 
//This are the if statements for my check boxes. My program executes the if statements even if the check boxes are not checked. what could be the problem. please help 
       if (result == result.append("Airtime: ").append(chkAirtime.isChecked())) { 
        balance = balance - 50; 

       } 

       if (result == result.append("Electricity: ").append(chkElectricity.isChecked())) { 
        balance = balance - 150; 
       } 

       if (result == result.append("Water: ").append(chkWater.isChecked())) { 
        balance = balance - 150; 
       } 

       if (result == result.append("Transfers: ").append(chkTransfer.isChecked())) { 

        balance = balance - 500; 
       } 

       if (result == result.append("Withdrawal: ").append(chkWithdrawal.isChecked())) { 

        balance = balance - 200; 
       } 

       if (result == result.append("Pay Dstv: ").append(chkPayDstv.isChecked())) { 

        balance = balance - 200; 

       } else { 
        Toast.makeText(SavingsAccountTransactions.this, "Nothing been Selected ", Toast.LENGTH_LONG).show(); 
       } 


       savingsBalance.setText("Your Balance is: " + balance); 
       Toast.makeText(SavingsAccountTransactions.this, result.toString(), Toast.LENGTH_SHORT).show(); 
      } 
     }); 

    } 

回答

1

很明顯,如果條件返回總是爲真。
(例如:result == result.append("Airtime: ").append(chkAirtime.isChecked())
爲什麼:您正在使用if條件相同的對象。

通過看你的代碼,我認爲你需要的,如果條件檢查這樣

if (chkAirtime.isChecked()) { //checking CheckBox is checked or not. 
    balance = balance - 50; 
    result.append("Airtime: "+balance+" ");//appending data to result 
} 

執行相同的所有其他。

重要:如果要比較兩個字符串總是使用equals。像s1.equals(s2);visit this : SO - Java String.equals versus ==

Happy_Coding;

+0

謝謝你的回答,幫了很多 – Nhlanhla

+0

很高興幫忙.. **:)** – Bharatesh