复选框出现太多吐司

时间:2013-06-11 23:04:37

标签: android if-statement checkbox toast

我有两个复选框和两个EditText。 CheckBox的OnClick使EditText消失,并显示Toast "Your Information is Saved"。如果再次单击CheckBox,则另一个Toast将显示"Enter Your Email Address"。虽然它正在工作,但Toast在一个onClick之后正好显示在彼此之后。任何想法?

on.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    if (((CheckBox) v).isChecked())
      receiverEmail.setVisibility(View.GONE);
    if (((CheckBox) v).isChecked())
      Toast.makeText(getApplicationContext(), 
      "Your Information is Saved", Toast.LENGTH_LONG).show();
    else
      receiverEmail.setVisibility(View.VISIBLE);
      Toast.makeText(getApplicationContext(), 
      "Enter Your Email Address", Toast.LENGTH_LONG).show();
  }
});

on2.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    if (((CheckBox) v).isChecked())
      clientID.setVisibility(View.GONE);
    if (((CheckBox) v).isChecked())
      Toast.makeText(getApplicationContext(), 
      "Your Information is Saved", Toast.LENGTH_LONG).show();
    else
      clientID.setVisibility(View.VISIBLE);
      Toast.makeText(getApplicationContext(), 
      "Enter Your Email Address", Toast.LENGTH_LONG).show();
  }
});

2 个答案:

答案 0 :(得分:1)

您正在错误地使用if/else循环。将您的setOnClickListener's更改为以下内容,它应该可以正常工作......

on.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    if (((CheckBox) v).isChecked()) {
      receiverEmail.setVisibility(View.GONE);
      Toast.makeText(getApplicationContext(), "Your Information is Saved", Toast.LENGTH_LONG).show();
    } else {
      receiverEmail.setVisibility(View.VISIBLE);
      Toast.makeText(getApplicationContext(), "Enter Your Email Address", Toast.LENGTH_LONG).show();
    }
  }
});

on2.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    if (((CheckBox) v).isChecked()) {
      clientID.setVisibility(View.GONE);
      Toast.makeText(getApplicationContext(), "Your Information is Saved", Toast.LENGTH_LONG).show();
    } else {
      clientID.setVisibility(View.VISIBLE);
      Toast.makeText(getApplicationContext(), "Enter Your Email Address", Toast.LENGTH_LONG).show();
    }
  }
});

答案 1 :(得分:0)

您在else语句后忘记了curlies,因此无论是否选中Toast,都会显示最后CheckBox

您的else语句应如下所示:

else {
    receiverEmail.setVisibility(View.VISIBLE);
    Toast.makeText(getApplicationContext(), 
    "Enter Your Email Address", Toast.LENGTH_LONG).show();
    }});
}

else {
    clientID.setVisibility(View.VISIBLE);
    Toast.makeText(getApplicationContext(), 
    "Enter Your Email Address", Toast.LENGTH_LONG).show();
    }});
}

我总是在每个if / else之后包含卷曲块以避免这样的情况,当缩进会诱使你相信第二个语句是if / else的一部分时,当它不是时。