赞
踩
问题
编写一个简单的登录页面,当用户输入正确的用户名和密码后,会跳转到欢迎页面,并在页面上显示“欢迎光临,用户名”。
源代码
activity_login.xml:
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" 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="match_parent" android:layout_height="wrap_content" android:text="登录" /> </LinearLayout>
LoginActivity.java:
public class LoginActivity extends AppCompatActivity { private EditText etUsername; private EditText etPassword; private Button btnLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); etUsername = findViewById(R.id.et_username); etPassword = findViewById(R.id.et_password); btnLogin = findViewById(R.id.btn_login); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String username = etUsername.getText().toString(); String password = etPassword.getText().toString(); // 判断用户名和密码是否正确 if (username.equals("admin") && password.equals("123456")) { // 登录成功,跳转到欢迎页面 Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class); intent.putExtra("username", username); startActivity(intent); } else { // 登录失败,弹出提示信息 Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show(); } } }); } }
activity_welcome.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/tv_welcome"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="欢迎光临,"
android:textSize="24sp" />
</LinearLayout>
WelcomeActivity.java:
public class WelcomeActivity extends AppCompatActivity { private TextView tvWelcome; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); tvWelcome = findViewById(R.id.tv_welcome); // 获取传递过来的用户名 String username = getIntent().getStringExtra("username"); // 在欢迎页面上显示“欢迎光临,用户名” tvWelcome.setText("欢迎光临," + username); } }
补充
Intent:
Intent跳转:
Intent intent =new Intent(源Activity的对象,目标Activity的class);
startActivity(intent);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。