android登录页面代码
以下是一个简单的Android登录页面代码示例:
activity_login.xml:
<?xml version="1.0" encoding="utf-8"?>
<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/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login" />
</LinearLayout>
LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
private EditText etUsername, 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();
// TODO: 进行登录验证
// 登录成功,跳转到主界面
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
}
在这个示例中,我们使用了一个LinearLayout来布局登录页面,包括一个EditText用于输入用户名,一个EditText用于输入密码,以及一个Button用于提交登录信息。在LoginActivity中,我们获取了这些控件的引用,并在按钮的点击事件中进行了登录验证。如果验证成功,我们就跳转到主界面。
在进行登录验证时,可以使用一些常见的方法,例如:
使用SharedPreferences保存用户名和密码,然后在登录时进行比对。
SharedPreferences preferences = getSharedPreferences("user_info", MODE_PRIVATE);
String savedUsername = preferences.getString("username", "");
String savedPassword = preferences.getString("password", "");
if (username.equals(savedUsername) && password.equals(savedPassword)) {
// 登录成功
} else {
// 登录失败
}
发送登录请求到服务器,服务器返回验证结果。
// 创建OkHttpClient对象
OkHttpClient client = new OkHttpClient();
// 创建请求体
RequestBody requestBody = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
// 创建请求对象
Request request = new Request.Builder()
.url("http://example.com/login")
.post(requestBody)
.build();
// 发送请求并获取响应
try {
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
if (response.isSuccessful() && responseBody.equals("success")) {
// 登录成功
} else {
// 登录失败
}
} catch (IOException e) {
e.printStackTrace();
}
需要注意的是,第二种方法需要在AndroidManifest.xml中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />