java Android Studio 页面跳转 - android:layout_width=&#34

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力神器 👁️ 134 次阅读

问题

编写一个简单的登录页面,当用户输入正确的用户名和密码后,会跳转到欢迎页面,并在页面上显示“欢迎光临,用户名”。

源代码

activity_login.xml: 拼多多帮助力入口

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

android:id="@+id/et_username"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="用户名" />

android:id="@+id/et_password"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="密码"

android:inputType="textPassword" />

android:id="@+id/btn_login"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="登录" />

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:

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

android:id="@+id/tv_welcome"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="欢迎光临,"

android:textSize="24sp" />

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:

Android中提供了Intent机制来协助应用间的交互与通讯,或者采用更准确的说法是,Intent不仅可用于应用程序之间,也可用于应用程序内部的activity,service和broadcast receiver之间的交互。Intent这个英语单词的本意是“目的、意向、意图”。Intent是一种运行时绑定(runtime binding)机制,它能在程序运行的过程中连接两个不同的组件。通过Intent,你的程序可以向Android表达某种请求或者意愿,Android会根据意愿的内容选择适当的组件来响应。

Intent跳转:

Intent intent =new Intent(源Activity的对象,目标Activity的class);

startActivity(intent);

推荐链接

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧