假设您从最后一页获得一个 int 值:
创建类:
public class GenericUtility {
public static int getIntFromSharedPrefsForKey(String key, Context context)
{
int selectedValue = 0;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
selectedValue = prefs.getInt(key, 0);
return selectedValue;
}
public static boolean setIntToSharedPrefsForKey(String key, int value, Context context)
{
boolean savedSuccessfully = false;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try
{
editor.putInt(key, value);
editor.apply();
savedSuccessfully = true;
}
catch (Exception e)
{
savedSuccessfully = false;
}
return savedSuccessfully;
}
public static String getStringFromSharedPrefsForKey(String key, Context context)
{
String selectedValue = "";
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
selectedValue = prefs.getString(key, "");
return selectedValue;
}
public static boolean setStringToSharedPrefsForKey(String key, String value, Context context)
{
boolean savedSuccessfully = false;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try
{
editor.putString(key, value);
editor.apply();
savedSuccessfully = true;
}
catch (Exception e)
{
savedSuccessfully = false;
}
return savedSuccessfully;
}
}
比给它设置int值:
GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, getApplicationContext());
或
GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, MyActivity.this))
在你想要结果的第一个活动中:
int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", getApplicationContext());
或
int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", MyActivity.this);
selectedValue 如果没有值,将返回默认值。
PS 在类中将 int 更改为 String 以相应地获取和设置结果。