什么是使用活动之间的共享preferences的最佳途径 [英] what is the Best way to use shared preferences between activities

查看:116
本文介绍了什么是使用活动之间的共享preferences的最佳途径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户preference在我的应用程序,这将会通过不同的活动UED。我想知道,利用不同活动之间的preferences在我的应用程序的最佳途径。

i have a user preference in my app, which gets ued by different activity. I would like to know the best way to utilise those preferences between different activities in my App.

予有这种想法从主活动创建共享preference对象,并从那里发送的意图的不同的活动采取行动。将它的工作?..或者只是保持从每一个活动叫getshared preferences()?谢谢你。

I have this idea to create a shared preference object from the main activity and from there send intents to the different activities to take actions. would it work?.. or just keep calling getsharedpreferences() from every activity?. Thank you.

推荐答案

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

Sending shared preferences through intents seems overcomplicated. You could wrap the shared preferences with something like the below and call the methods directly from your activities:

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

这篇关于什么是使用活动之间的共享preferences的最佳途径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆