You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何为现有Android登录功能添加记住用户名和密码复选框?

Adding "Remember Username & Password" to Your Android Login

Hey there! Adding a "Remember Me" checkbox to your login flow is straightforward using Android's SharedPreferences—it’s designed for storing small, persistent pieces of data exactly like login credentials. Let’s walk through how to implement this with your existing code.

Step 1: Add the CheckBox to Your Layout

First, open your login activity’s XML layout file (e.g., activity_login.xml) and add a CheckBox below your password field:

<CheckBox
    android:id="@+id/checkbox_remember_me"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Remember Username & Password"
    android:layout_marginTop="16dp"
    android:layout_below="@+id/et_password"/> <!-- Adjust layout constraints to match your UI -->

Make sure your existing EditText fields for username and password have unique IDs (e.g., et_username and et_password) so we can reference them in code.

Step 2: Update Your Login Activity Code

Modify your Logi activity to handle saving, loading, and clearing credentials based on the checkbox state. Here’s the updated code with explanations:

package no.vfk.vfkhakkespettboka;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.content.SharedPreferences;

public class Logi extends AppCompatActivity {

    private EditText etUsername, etPassword;
    private CheckBox cbRememberMe;
    private SharedPreferences loginPrefs;
    private SharedPreferences.Editor loginPrefsEditor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // Initialize UI elements
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        cbRememberMe = findViewById(R.id.checkbox_remember_me);
        Button btnLogin = findViewById(R.id.btn_login);

        // Initialize SharedPreferences (private mode = only your app can access this data)
        loginPrefs = getSharedPreferences("LoginCredentials", MODE_PRIVATE);
        loginPrefsEditor = loginPrefs.edit();

        // Load saved credentials if "Remember Me" was checked before
        loadSavedCredentials();

        // Login button click handler
        btnLogin.setOnClickListener(v -> {
            String username = etUsername.getText().toString().trim();
            String password = etPassword.getText().toString().trim();

            // Replace this with your existing login validation logic
            if (isValidLogin(username, password)) {
                // Handle checkbox state
                if (cbRememberMe.isChecked()) {
                    saveCredentials(username, password);
                } else {
                    clearCredentials();
                }

                // Navigate to your main activity (adjust class name as needed)
                startActivity(new Intent(Logi.this, MainActivity.class));
                finish();
            } else {
                Toast.makeText(Logi.this, "Invalid username or password", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // Save credentials to SharedPreferences
    private void saveCredentials(String username, String password) {
        loginPrefsEditor.putString("saved_username", username);
        loginPrefsEditor.putString("saved_password", password);
        loginPrefsEditor.putBoolean("remember_me", true);
        loginPrefsEditor.apply(); // Use apply() for async saving (more efficient than commit())
    }

    // Load saved credentials into input fields
    private void loadSavedCredentials() {
        boolean rememberMe = loginPrefs.getBoolean("remember_me", false);
        if (rememberMe) {
            String savedUser = loginPrefs.getString("saved_username", "");
            String savedPass = loginPrefs.getString("saved_password", "");
            etUsername.setText(savedUser);
            etPassword.setText(savedPass);
            cbRememberMe.setChecked(true);
        }
    }

    // Clear saved credentials if "Remember Me" is unchecked
    private void clearCredentials() {
        loginPrefsEditor.remove("saved_username");
        loginPrefsEditor.remove("saved_password");
        loginPrefsEditor.putBoolean("remember_me", false);
        loginPrefsEditor.apply();
    }

    // Replace this with your actual login validation logic
    private boolean isValidLogin(String username, String password) {
        // Example validation: check against hardcoded values (replace with your API/db check)
        return username.equals("testuser") && password.equals("testpass");
    }
}

Important Notes

  • Security Warning: SharedPreferences stores data in plain text by default. For production apps, you should encrypt sensitive data like passwords. Use Android's Jetpack Security library to implement EncryptedSharedPreferences for secure storage.
  • Layout Adjustments: Make sure the CheckBox is positioned correctly in your XML layout (adjust layout_below, layout_margin, etc., to match your existing UI).
  • Validation Logic: Replace the isValidLogin() method with your actual login validation (e.g., API call, database check).

内容的提问来源于stack exchange,提问作者Marius Wik

火山引擎 最新活动