0

I added two check box in the on create method

  checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
  checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
  checkBox1.setOnCheckedChangeListener(this) ; 
  checkBox2.setOnCheckedChangeListener(this) ;

the main function of the check boxes that when ischeck() a picture will be added to the mainlayout and when uncheck the picture will be removed >> I used the code bellow, the first check box is working fine the second check box when I do check it shows the pics and then they I can remove them even with uncheck ... where is the wrong in my code ??

   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

// TODO Auto-generated method stub
if(checkBox1.isChecked())
{ 

    ......
    mapOverlays.add(custom); 
}
else {
    mapOverlays.remove(custom)  ;
}

if (checkBox2.isChecked())
{
    ....

    mapOverlays.add(custom2);
}
else 
{
    mapOverlays.remove(custom2)  ;
}
}
}
4

2 に答える 2

2

2番目のチェックボックスのチェックを別の方法で処理しています。コードは次のようになりますか?

if (checkBox2.isChecked())
{
    ...
    mapOverlays.add(custom2);
}
else
{
    mapOverlays.remove(custom2);
}

Upd:コードが現在の編集のように見える場合、問題はブロックcustom2内の変数の宣言です。if追加されたmapOverlayではなく、別の場所で宣言された別のものを削除しています。

交換するだけ

if (checkBox2.isChecked())
{
    MapItemizedOverlay custom2 = ...

if (checkBox2.isChecked())
{
    custom2 = ...

Upd2:メソッドにはさらに別の問題がありますonCheckedChanged()。最初if-elseは、checkBox1 のチェック/チェック解除だけでなく、checkBox2 のチェック/チェック解除でも実行されます。2 つ目も同じですif-else

メソッドを書き直してみてください:

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (buttonView.equals(checkBox1)) {
        // first if-else
    } else if (buttonView.equals(checkBox2)) {
        // second if-else
    }
}

またはさらに良い:

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (buttonView.getId() == R.id.checkBox1) {
        if (isChecked) { 
            ...
            mapOverlays.add(custom);
        } else {
            mapOverlays.remove(custom);
        }
    } else if (buttonView.getId() == R.id.checkBox2) {
        if (isChecked) { 
            ...
            mapOverlays.add(custom2);
        } else {
            mapOverlays.remove(custom2);
        }
    }
}
于 2012-07-10T08:41:01.563 に答える
0

チェックボックス2にもcheckedchangelistenerを追加する必要があります。

checkBox2.setOnCheckedChangeListener(this) ; 
于 2012-07-10T08:38:34.207 に答える