什么是在活动之间使用共享偏好的最佳方式

iro*_*xxx 18 android sharedpreferences

我的应用程序中有一个用户首选项,可供不同的活动使用.我想知道在我的应用程序中不同活动之间使用这些首选项的最佳方法.

我有这个想法从主活动创建一个共享首选项对象,并从那里发送意图到不同的活动来采取行动.那会有用吗?

或者只是继续getsharedpreferences()从每个活动打电话......?

谢谢.

for*_*all 25

通过意图发送共享首选项似乎过于复杂.您可以使用下面的内容包装共享首选项,并直接从您的活动中调用方法:

public class Prefs {
    private static String MY_STRING_PREF = "mystringpref";
    private static String MY_INT_PREF = "myintpref";

    private static SharedPreferences getPrefs(Context context) {
        return context.getSharedPreferences("myprefs", 0);
    }

    public static String getMyStringPref(Context context) {
        return getPrefs(context).getString(MY_STRING_PREF, "default");
    }

    public static int getMyIntPref(Context context) {
        return getPrefs(context).getInt(MY_INT_PREF, 42);
    }

    public static void setMyStringPref(Context context, String value) {
        // perform validation etc..
        getPrefs(context).edit().putString(MY_STRING_PREF, value).commit();
    }

    public static void setMyIntPref(Context context, int value) {
        // perform validation etc..
        getPrefs(context).edit().putInt(MY_INT_PREF, value).commit();
    }
}
Run Code Online (Sandbox Code Playgroud)


kru*_*hah 6

您可以使用这种方式,并在要使用的所有活动中声明具有相同名称的相同变量.

  public static final String PREFS_NAME = "MyPrefsFile";
  static SharedPreferences settings;
  SharedPreferences.Editor editor;
  int wordCount;

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    settings = getSharedPreferences(PREFS_NAME, 0);
    editor = settings.edit();

    wordCount = settings.getInt("wordCount", 4); 

  }
Run Code Online (Sandbox Code Playgroud)

这里最初wordCount将给出4; 当你编辑wordCount并想再次存储时

  editor.putInt("wordCount", 6);
  editor.commit();
Run Code Online (Sandbox Code Playgroud)

您必须在要使用共享首选项的活动中声明此相同的变量.最好在每个活动中调用getSharedPreferences.

我不认为在意图中传递这种偏好是有效的.