复选框android

时间:2012-07-10 08:34:59

标签: android google-maps android-layout checkbox

我在on create method

中添加了两个复选框
  checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
  checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
  checkBox1.setOnCheckedChangeListener(this) ; 
  checkBox2.setOnCheckedChangeListener(this) ;

复选框的主要功能,当缺席()时,图片将被添加到主布局,当取消选中时,图片将被移除>>我使用下面的代码,第一个复选框工作正常第二个复选框,当我检查它显示图片然后他们我可以删除它们甚至取消选中...我的代码在哪里错了?

   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)  ;
}
}
}

2 个答案:

答案 0 :(得分:2)

您正在以不同方式处理第二个复选框。可能代码应该是这样的吗?

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

更新:如果您的代码在当前编辑中显示,则问题是custom2块中的声明if变量。您正在删除未添加的mapOverlay,但另一个已在其他地方声明。

只需替换

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

通过

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

更新2:您的onCheckedChanged()方法还存在另一个问题。第一个if-else不仅在checkBox1上检查/取消选中,还在checkBox2上检查/取消选中。第二个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);
        }
    }
}

答案 1 :(得分:0)

您还需要将checkedchangelistener添加到复选框2中。

checkBox2.setOnCheckedChangeListener(this) ;