我是android的新手。已经学习了一些属性..尝试通过将输入的字符串与静态的硬编码字符串进行比较来验证用户身份。我正在设置“登录”按钮的文本,将消息发布为“正确密码”或“密码不正确!” ,但每次“不正确的密码!”消息仅打印在按钮上。
这是代码..
public class MainActivity extends Activity implements OnClickListener {
Button btnLogin;
EditText etUsername;
EditText etPassword;
TextView tvUname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText)findViewById(R.id.editText1);
etPassword = (EditText)findViewById(R.id.editText2);
btnLogin = (Button)findViewById(R.id.button1);
btnLogin.setOnClickListener(this);
}
这是OnClick方法的代码!
@Override
public void onClick(View v) {
String uname = "abhi";
String pass = "test";
if(uname == etUsername.getText().toString() && pass == etPassword.getText().toString()){
btnLogin.setText("Correct Password!");
}
else{
btnLogin.setText("Incorrect Password!");
}
}
}
请帮帮我..!
答案 0 :(得分:2)
比较String
时使用equals
您将int, double, float, long and boolean
与==
答案 1 :(得分:0)
试试这个
if( (uname == etUsername.getText().toString() ) && ( pass == etPassword.getText().toString() )){
btnLogin.setText("Correct Password!");
}
答案 2 :(得分:0)
Android幸运地有TextUtils.equals()进行文字比较
所以你可以这样做:
private boolean isAutheticated(CharSequence username, CharSequence password) {
String uname = "abhi";
String pass = "test";
//Check if they match and return the result
return TextUtils.equals(uname, username) && TextUtils.equals(pass, password);
}
@Override
public void onClick(View v) {
if(isAuthenticated(etUsername.getText(), etPassword.getText())) {
btnLogin.setText("Correct Password!");
} else {
btnLogin.setText("Incorrect Password!");
}
}