Android 跨页面传递数据:账号密码验证并显示
Android 跨页面传递数据:账号密码验证并显示
本文将介绍如何在Android应用中使用Intent传递数据,实现账号密码验证后将输入内容在另一个页面显示的功能。
一、第一个页面代码
TextView sr = findViewById(R.id.editTextNumberPassword);
TextView sr1 = findViewById(R.id.editTextNumber);
Button loginButton = findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = sr.getText().toString();
String password = sr1.getText().toString();
if (username.equals('feng') && password.equals('12345')) {
Intent intent = new Intent(MainActivity3.this, MainActivity2.class);
intent.putExtra('username', username);
intent.putExtra('password', password);
startActivity(intent);
} else {
Toast.makeText(MainActivity3.this, '账号或者密码不正确', Toast.LENGTH_LONG).show();
}
}
});
代码说明:
- 获取输入的账号和密码。
- 验证账号密码是否正确。
- 创建一个Intent对象,并设置目标Activity为MainActivity2.class。
- 使用
putExtra()方法将账号和密码添加到Intent中。 - 使用
startActivity()方法启动第二个页面。
二、第二个页面布局文件
<TextView
android:id="@+id/usernameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/passwordTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
代码说明:
- 添加两个TextView控件用于显示账号和密码。
三、第二个页面代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView usernameTextView = findViewById(R.id.usernameTextView);
TextView passwordTextView = findViewById(R.id.passwordTextView);
Intent intent = getIntent();
String username = intent.getStringExtra('username');
String password = intent.getStringExtra('password');
usernameTextView.setText('账号: ' + username);
passwordTextView.setText('密码: ' + password);
}
代码说明:
- 获取传递过来的Intent对象。
- 使用
getStringExtra()方法获取账号和密码。 - 将获取的账号和密码设置到TextView控件中。
四、总结
通过以上步骤,实现了账号密码验证并显示的功能。使用Intent传递数据是Android应用之间进行数据交互的重要方式,可以方便地实现不同页面之间的数据共享。
原文地址: https://www.cveoy.top/t/topic/o9ui 著作权归作者所有。请勿转载和采集!