2015-10-10 65 views
0

我正在嘗試創建一個簡單的安卓遊戲,其中10個複選框隨機出現在屏幕上,並且必須儘快檢查所有這些複選框。然後所有複選框被刪除。代碼的第一部分工作,創建了10個複選框。但是,如果我添加代碼的第二部分,它根本不起作用,甚至沒有複選框出現,應用程序凍結。複選框遊戲無法正常工作

public void checkbox(View v){ CheckBox [] cb = new CheckBox [10];

RelativeLayout r = (RelativeLayout) findViewById(R.id.layout); 
    for (int i = 0; i < 10; i++) { 
     cb[i] = new CheckBox(this); 
     CheckBox c =cb[i]; 
     int randy = (int) Math.floor(Math.random() * 1100 + 90); 
     int randx = (int) Math.floor(Math.random() * 600); 

     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(90, 90); 
     params.leftMargin = randx; 
     params.topMargin = randy; 
     c.setId(i); 
     r.addView(c, params);} 

    while (!checked(cb)){} //wait untill checked(cb)=true 
    r.removeAllViews(); 

} 
public boolean checked(CheckBox[] cb) { //returns true if all checkboxes are checked 
boolean b = true; 
    for (CheckBox c:cb) 
    { 
     if (!c.isChecked()){ 
      b=false; 
     } 
    } 


    return b; 

} 

編輯的代碼:

int CheckedCount = 0; 
int j = 0; 
CheckBox[] cb = new CheckBox[10]; 
Boolean[] checked = new Boolean[10]; 

public void checkbox(View v) { 
    Arrays.fill(checked, Boolean.FALSE); 
    RelativeLayout r = (RelativeLayout) findViewById(R.id.layout); 
    for (j = 0; j < 10; j++) { 
     cb[j] = new CheckBox(this); 
     CheckBox c =cb[j]; 
     int randy = (int) Math.floor(Math.random() * 1100 + 90); 
     int randx = (int) Math.floor(Math.random() * 600); 

     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(90, 90); 
     params.leftMargin = randx; 
     params.topMargin = randy; 
     c.setId(j); //id set for each checkbox 
     c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(CompoundButton compoundButton, boolean b) { 
       //missing code 

       boolean c =true; 
       for (boolean d:checked){ 
        if (!d){ 
         c=false; 
        } 
       } 

       if (c) { 
        RelativeLayout r = (RelativeLayout) findViewById(R.id.layout); 
        r.removeAllViews(); 
       } 
    /*   //old code 
       CheckedCount++; 
       if (CheckedCount == 10) { 
      RelativeLayout r = (RelativeLayout) findViewById(R.id.layout); 
        for (int a= 0; a<10;a++){ 
         CheckBox c = cb[i]; 
         r.removeView(c); 
        } 
        r.removeAllViews(); 
       }*/ 
      } 
     }); 
     r.addView(c, params); 

    } 

}} 

回答

0

使用while循環並不確定在用戶界面的變化正確的方法。相反,我建議你爲每個複選框添加一個監聽器,然後檢查複選框的狀態(使用'checked'等方法)。

+0

它的工作,但只有一個聽衆。我如何實現onCheckedChanged監聽器爲每個複選框創建一個監聽器? – mbostic

+0

您應該將其添加到方法'複選框'的循環中,並在偵聽器中調用'checked'。 –

+0

我在上面添加了編輯後的代碼。首先,我嘗試在每次選中複選框時將其遞增計數(標記爲//舊代碼)。它的工作,但問題是,我可以檢查並取消選中一個複選框10次。爲了解決這個問題,我做了一些錯誤的布爾值。每次點擊複選框時,與複選框相同索引的數組中的布爾值將設置爲true。但問題是,我不知道如何獲取在偵聽器方法中檢查的複選框的索引。 – mbostic