用Android studio实现登录功能,用户输入用户名和密码,假设用户的用户名为zhangsan,密码为123123,当用户正确输入用户名和密码时用Toast弹出提示“恭喜你,登录成功!”,否则提示“对不起,用户名或密码错误!”
时间: 2024-05-12 08:20:35 浏览: 9
以下是实现登录功能的代码示例:
MainActivity.java:
```
public class MainActivity extends AppCompatActivity {
private EditText etUsername, etPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_password);
Button btnLogin = findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login();
}
});
}
private void login() {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if (username.equals("zhangsan") && password.equals("123123")) {
Toast.makeText(this, "恭喜你,登录成功!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "对不起,用户名或密码错误!", Toast.LENGTH_SHORT).show();
}
}
}
```
activity_main.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用户名" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"
android:inputType="textPassword" />
<Button
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录" />
</LinearLayout>
```
以上代码实现了在Android Studio中实现登录功能。用户输入用户名和密码,如果用户名和密码正确,则用Toast弹出提示“恭喜你,登录成功!”,否则提示“对不起,用户名或密码错误!”。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![csv](https://img-home.csdnimg.cn/images/20210720083646.png)
![mp4](https://img-home.csdnimg.cn/images/20210720083504.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)