如果在按钮上点击监听器的android中的条件错误

时间:2013-10-27 10:26:30

标签: java android string

public class MainActivity extends Activity {

    EditText t1,t2;
    TextView v1,v2;
    String username1 = "admin";
    String password1 = "12345";
    Button b1;
    String user;
    Context c;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        c = getApplicationContext();
        t1 = (EditText) findViewById(R.id.editText1);
        t2 = (EditText) findViewById(R.id.editText2);
        b1 = (Button) findViewById(R.id.button1);
        v1 = (TextView) findViewById(R.id.textView1);
        v2 = (TextView) findViewById(R.id.textView2);
        v1.setTextColor(Color.WHITE);
        v2.setTextColor(Color.WHITE);
        button();
    }

    public void button()
    {
         b1.setOnClickListener(new OnClickListener() {
             public void onClick(View v) {
                 user = t1.getText().toString();
                 String pass = t2.getText().toString();

                 if(user == username1 && pass == password1)
                 {
                     Intent aa = new Intent(MainActivity.this, admin.class);
                     startActivity(aa);
                 }
                 else
                 {
                     Toast.makeText(c, "username or password is incorrect",Toast.LENGTH_LONG).show(); 
                 }

             }
         });
    }

}

每次执行其他块时,如果条件为真或错,那么该程序的问题是什么,请告诉我答案......

2 个答案:

答案 0 :(得分:0)

if(user == username1 && pass == password1) 

应该是

if(user.equals(username1) && pass.equals(password1))

这是因为您正在比较String对象

答案 1 :(得分:0)

字符串比较由equals运算符完成。请尝试下面的代码

 if(user.equals(username1) && pass.equals(password1))