0

我有两个复选框和两个 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();
  }
});
4

2 回答 2

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();
    }
  }
});
于 2013-06-11T23:17:47.800 回答
0

您忘记了else语句后的花括号,因此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 的一部分,而实际上它不是。

于 2013-06-11T23:06:45.633 回答