Checkbox游戏无法正常工作

时间:2015-10-10 17:16:34

标签: java android checkbox

我正在尝试创建一个简单的Android游戏,其中10个复选框随机出现在屏幕上,您必须尽可能快地检查所有这些复选框。然后删除所有复选框。代码的第一部分工作,创建了10个复选框。但是如果我添加代码的第二部分它根本不起作用,甚至没有复选框出现和应用冻结。

public void复选框(查看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);

    }

}}

1 个答案:

答案 0 :(得分:0)

使用while循环不是确定UI中更改的正确方法。相反,我建议您为每个复选框添加一个onCheckedChanged事件的监听器,然后选中复选框&#39;状态(使用&#39;检查&#39;等方法)。

相关问题