Android - 始终有效的else语句

时间:2015-06-12 15:30:48

标签: android

  public void myClick1(View v){
    EditText txtUser = (EditText) findViewById(R.id.strUser);
    EditText txtPwd = (EditText)findViewById(R.id.strPwd);

  if (txtUser.equals("admin")){
        Toast.makeText(getApplicationContext(),"Authentication Pass", Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(getApplicationContext(),"Not valid User ID/Password: " + txtUser.getText(), Toast.LENGTH_LONG).show();
}

无论我键入文本框,它总是激活else语句。为什么呢?

3 个答案:

答案 0 :(得分:1)

比较时应该使用txtUser.getEditableText()。toString():

if ("admin".equals(txtUser.getEditableText().toString())){
    Toast.makeText(getApplicationContext(),"Authentication Pass", Toast.LENGTH_LONG).show();
}else{
    Toast.makeText(getApplicationContext(),"Not valid User ID/Password: " + txtUser.getText(), Toast.LENGTH_LONG).show();

答案 1 :(得分:0)

您必须获取TextView的文本,如下所示:

    EditText txtUser = (EditText) findViewById(R.id.strUser);
    EditText txtPwd = (EditText) findViewById(R.id.strPwd);

    if ("admin".equals(txtUser.getText().toString())) {
        Toast.makeText(getApplicationContext(), "Authentication Pass", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(),"Not valid User ID/Password: " + txtUser.getText(), Toast.LENGTH_LONG).show();
    }

答案 2 :(得分:-2)

我对android atm并不熟悉,但你试过了吗?

  

txtUser.getText()==“admin”

感谢您的评论(我使用的是C#方法),修复了代码:

txtUser.getText().equals("admin")