Android studio 编写一个页面登录和跳转成功的代码
时间: 2024-05-15 17:13:59 浏览: 19
这里提供一个简单的示例代码,实现了一个登录页面(LoginActivity)和一个跳转成功页面(SuccessActivity)。
LoginActivity.java:
```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 v) {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if (username.equals("admin") && password.equals("123456")) {
Intent intent = new Intent(LoginActivity.this, SuccessActivity.class);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
}
}
});
}
}
```
SuccessActivity.java:
```java
public class SuccessActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_success);
}
}
```
activity_login.xml:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用户名"
android:padding="16dp" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"
android:inputType="textPassword"
android:padding="16dp"
android:layout_below="@id/et_username"/>
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录"
android:layout_below="@id/et_password"/>
</RelativeLayout>
```
activity_success.xml:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录成功!"
android:textSize="24sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
```
这个示例代码实现了一个简单的登录页面,用户输入用户名和密码后,点击登录按钮进行验证,如果用户名和密码正确,则跳转到成功页面。如果用户名或密码错误,则会弹出一个提示框告知用户。