代码展示(错误)
public static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.获取账号密码信息
EditText edit_username = findViewById(R.id.username);
final String username = edit_username.getText().toString();
//在日志里打印下账号
Log.i(TAG,"账号为:"+username);
EditText edit_passwd = findViewById(R.id.passwd);
final String passwd = edit_passwd.getText().toString();
//在日志里打印下密码
Log.i(TAG,"密码为:"+passwd);
Button btn_login = findViewById(R.id.button);
final TextView hint = findViewById(R.id.tv1);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/**
* 测试用户名为admin,密码123456
*
*/
if (username.equals("admin")) {
if (passwd.equals("123456")) {
hint.setText("登陆成功");
} else {
hint.setText("密码错误");
}
} else {
hint.setText("账号错误");
}
}
});
}
运行结果
(注:这里我是输入了账号密码的,没截图)
问题分析
也就是获取到的值都是空,后面就一直是账号错误
后来看到别人的博客才发现是我傻了。。
editText的值是要在发生点击事件之后才能获得用户输入进去的值。。。。
代码展示(正确)
public static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.获取账号密码的EidtText控件
final EditText edit_username = findViewById(R.id.username);
final EditText edit_passwd = findViewById(R.id.passwd);
//2. 获取按钮的控件
Button btn_login = findViewById(R.id.button);
final TextView hint = findViewById(R.id.tv1);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/**
* 测试用户名为admin,密码123456
*
*/
//注:这两个要点击之后才能取得输入的值。。
//3. 对账号密码进行判断
String username = edit_username.getText().toString();
String passwd = edit_passwd.getText().toString();
if (username.equals("admin")) {
if (passwd.equals("123456")) {
hint.setText("登陆成功");
} else {
hint.setText("密码错误");
}
} else {
hint.setText("账号错误");
}
}
});
}