Android studio 编写登录注册代码
时间: 2024-02-12 21:02:25 浏览: 17
以下是一个简单的示例代码,用于实现登录和注册功能:
1. activity_login.xml 布局文件:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/username_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"/>
<EditText
android:id="@+id/password_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
<Button
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"/>
<Button
android:id="@+id/register_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"/>
</LinearLayout>
```
2. LoginActivity.java 代码:
```
public class LoginActivity extends AppCompatActivity {
private EditText mUsernameEditText;
private EditText mPasswordEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mUsernameEditText = findViewById(R.id.username_edit_text);
mPasswordEditText = findViewById(R.id.password_edit_text);
Button loginButton = findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = mUsernameEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
// 处理登录逻辑
if (TextUtils.isEmpty(username)) {
Toast.makeText(LoginActivity.this, "Please enter your username", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(password)) {
Toast.makeText(LoginActivity.this, "Please enter your password", Toast.LENGTH_SHORT).show();
} else {
// 登录成功
Toast.makeText(LoginActivity.this, "Login success", Toast.LENGTH_SHORT).show();
}
}
});
Button registerButton = findViewById(R.id.register_button);
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = mUsernameEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
// 处理注册逻辑
if (TextUtils.isEmpty(username)) {
Toast.makeText(LoginActivity.this, "Please enter your username", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(password)) {
Toast.makeText(LoginActivity.this, "Please enter your password", Toast.LENGTH_SHORT).show();
} else {
// 注册成功
Toast.makeText(LoginActivity.this, "Register success", Toast.LENGTH_SHORT).show();
}
}
});
}
}
```
以上代码仅供参考,实际情况需要根据具体需求进行修改。