我在我的应用程序,其中被使用的不同的活动的用户偏好。我想知道利用我的应用程序的不同活动之间的那些喜好的最佳途径。

我有这种想法从主活动,并从那里发送的意图的各种活动的采取行动创建共享偏好对象。将这项工作...?

或者自顾自地从每一个活动叫getsharedpreferences() ..?

感谢。

有帮助吗?

解决方案

通过意图发送共享偏好似乎过于复杂。你可以下面类似的包裹共享偏好,并直接从您的活动调用的方法:

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();
    }
}

其他提示

您可以用这种方式,并宣布与要使用中的所有活动相同的名称相同的变量。

  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); 

  }

下面的wordCount最初会给4; 而当你的wordCount编辑,并希望再次存储

  editor.putInt("wordCount", 6);
  editor.commit();

您必须在您要使用共享偏好活动声明此相同的变量。而其更好的你打电话getSharedPreferences在每一个活动。

我不认为传递意图将工作是首选项。

您当然可以使用的共享偏好在您的应用程序。

如果你有不止一个简单的类型不是字符串或整型,你可以使用一个单独或扩展,这将是由你的应用程序的所有活动访问的应用程序类。 =>在这里无人接盘。简单地保存在存储器中。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top