用Android studio实现一个登录功能,用户输入用户名和密码,假设用户的用户名为zhangsan,密码为123123,当用户正确输入用户名和密码时用Toast弹出提示“恭喜你,登录成功!”,否则提示“对不起,用户名或密码错误!”
时间: 2024-05-24 18:10:30 浏览: 23
首先,我们需要在Android Studio中创建一个新的工程,并在布局文件中添加两个EditText分别用于输入用户名和密码,以及一个Button用于登录。
接下来,我们需要在MainActivity中编写代码来实现登录功能。具体步骤如下:
1. 获取输入的用户名和密码:
```
EditText etUsername = findViewById(R.id.et_username);
EditText etPassword = findViewById(R.id.et_password);
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
```
2. 判断用户名和密码是否正确:
```
if (username.equals("zhangsan") && password.equals("123123")) {
// 登录成功,弹出提示
Toast.makeText(this, "恭喜你,登录成功!", Toast.LENGTH_SHORT).show();
} else {
// 登录失败,弹出提示
Toast.makeText(this, "对不起,用户名或密码错误!", Toast.LENGTH_SHORT).show();
}
```
3. 将以上代码放入登录按钮的OnClickListener中,即可实现登录功能:
```
Button btnLogin = findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText etUsername = findViewById(R.id.et_username);
EditText etPassword = findViewById(R.id.et_password);
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if (username.equals("zhangsan") && password.equals("123123")) {
// 登录成功,弹出提示
Toast.makeText(MainActivity.this, "恭喜你,登录成功!", Toast.LENGTH_SHORT).show();
} else {
// 登录失败,弹出提示
Toast.makeText(MainActivity.this, "对不起,用户名或密码错误!", Toast.LENGTH_SHORT).show();
}
}
});
```
最终效果如下图所示:
![登录界面](https://img-blog.csdnimg.cn/2021110319321095.png)
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)