如何验证特定密码的密码字段,例如coolhack
,如Android中的情况?
以下是代码:
public class MainActivity extends AppCompatActivity {
Button buttn;
EditText passwrd;
String str, str1 = "coolhack";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
passwrd = (EditText) findViewById(R.id.password);
str = passwrd.getText().toString();
buttn = (Button) findViewById(R.id.button1);
buttn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
validate();
}
});
}
private void validate() {
if(str.equals(str1)) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
} else {
Toast.makeText(MainActivity.this, "INVALID PASSWORD", Toast.LENGTH_SHORT).show();
}
}
}
答案 0 :(得分:1)
你需要移动
str = passwrd.getText().toString();
在onClick(或验证方法)
中目前,在加载Activity时,您会立即获得一个空字符串。
您希望对进行反应
答案 1 :(得分:0)
public class MainActivity extends AppCompatActivity {
Button buttn;
EditText passwrd;
String str, str1 = "coolhack";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
passwrd = (EditText) findViewById(R.id.password);
buttn = (Button) findViewById(R.id.button1);
buttn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
str = passwrd.getText().toString().trim();
validate();
}
});
}
private void validate() {
if(str.equals(str1)) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
} else {
Toast.makeText(MainActivity.this, "INVALID PASSWORD", Toast.LENGTH_SHORT).show();
}
}
}
点击按钮时从edittext获取字符串。