首先让我们尝试在 SharedPreferences 中保存一些东西,我正在使用一种方法,因为这种方法很容易理解,而且看起来很酷:P
在课堂上添加:
private SharedPreferences settings;
private static final String PREFS_NAME = "app_name";
private TextView usernameTextView;
private TextView passwordTextView;
init textviews...
usernameTextView = (TextView)...
passwordTextView= (TextView)...
在构造函数中添加:
settings = context.getSharedPreferences(
PREFS_NAME, 0);
--保存用户名和密码
public static final String USERNAME = "username";
public static final String PASSWORD= "password";
private void savePreferences(String sharedUsername, String sharedPassword) {
SharedPreferences.Editor SharedEditor = settings.edit();
SharedEditor.putString(USERNAME,
sharedUsername);
SharedEditor.putString(PASSWORD,
sharedPassword);
SharedEditor.commit();
}
--在文本视图中加载并显示用户名和密码
private void loadSharedPreferences() {
if (settings != null) {
String loadUsername= settings.getString(
USERNAME , null);
if (loadUsername != null && !loadUsername.isEmpty()) {
usernameTextView.setText(loadUsername);
}
String loadPassword= settings.getString(
PASSWORD, null);
if (loadPassword!= null && !loadPassword.isEmpty()) {
passwordTextView.setText(loadPassword);
}
}
}
希望你使用它。干杯