SharedPreferences和Application类 [英] SharedPreferences and Application class

查看:106
本文介绍了SharedPreferences和Application类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我的应用有很多共同的偏好(主要与颜色自定义有关),我不确定在运行时存储/使用它们的最佳方法是什么.

I have many shared preference for my app (mostly relating to color customization) and I'm unsure what the best method is to store/use them at runtime.

目前,我在每个活动/片段中都在做这样的事情(根据视图的不同,偏好有所不同)

Currently I am doing something like this (with more or less preferences depending on the view) in every activity/fragment:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
int buttonbg = settings.getInt("buttonmenu_bg", 0);
int buttontxt = settings.getInt("buttonmenu_txt", 0);
int headerclr = settings.getInt("header", 0);

然后使用这些设置来设置显示屏中的各种颜色.每次都要调用PreferenceManager并完成所有这些工作似乎有很多开销.

And then using those to set the various colors in the display. This seems like a lot of overhead to have to call the PreferenceManager each time and go through all that.

因此,我开始着眼于创建一个应用程序类,一次读取首选项,并使用活动/片段中应用程序类中的静态变量来设置显示.

So I started looking at creating an application class, reading the preferences in once and using static variables from the application class in the activities/fragment to set the display.

我的问题是,在进一步冒险进入Application类路径之前,是否应该考虑这样做的缺点或陷阱?

My question is, are there any drawbacks or gotchas to doing this that I should consider before I venture further down the Application class path?

推荐答案

The purpose of the Application class is to store global application state or data (in memory of course), so your approach is correct. I've used it multiple times and it works like a charm.

我通常要做的是创建一个Map成员变量,并提供获取值和将值放入其中的方法,如下所示:

What I usually do is to create a Map member variable and provide methods for getting and putting values into it, looks like this:

package com.test;
...
...
public class MyApp extends Application{

    private Map<String, Object> mData;

    @Override
    public void onCreate() {
        super.onCreate();
        mData = new HashMap<String, Object>();
    }

    public Object get(String key){
        return mData.get(key);
    }
    public void put(String key,Object value){
        mData.put(key, value);
    }
}

然后从我的活动中,我只执行((MyApp) getApplication()).get("key")((MyApp) getApplication()).put("key",object).另外,不要忘记在清单文件中的application标记下设置android:name属性:

Then from my activities, I just do ((MyApp) getApplication()).get("key") or ((MyApp) getApplication()).put("key",object). Also, don't forget to set the android:name attribute in your manifest file, under the application tag:

<application
        ...
        ...
        android:name="com.test.MyApp"> 
</application>

这篇关于SharedPreferences和Application类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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