安卓:使用共享preferences在图书馆 [英] Android: using SharedPreferences in a library

查看:99
本文介绍了安卓:使用共享preferences在图书馆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了,我在我的应用程序中使用的库。我希望它访问存储在共享preferences一些设置。

I made a library that I use across my app. I want it to access some settings that are stored in the shared preferences.

这是我的图书馆的缩短版:

This is a shortened version of my library:

package com.android.foobar;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class Lib {
    int now;

    public Lib() {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        now = settings.getInt("now", 435);
    }

    public int foo(){
        return now;
    }
}

我一直在寻找一个答案和实验,但我无法找到一个有效的上下文传递给getDefaultShared preferences()。任何想法?

I've been looking for an answer and experimenting, but I can't find a valid context to pass to getDefaultSharedPreferences(). Any ideas?

推荐答案

最简单的方法是将包括上下文的库构造函数的参数,并通过从那里创建您的库点的应用程序上下文。

The most easiest way would be to include the context as a parameter of your Lib constructor and pass the application context from the point where your Lib is created.

如果您搜索的如何做到这一点看看这是一个静态的方式:<一href=\"http://stackoverflow.com/questions/3806051/accessing-shared$p$pferences-through-static-methods/3806138#3806138\">http://stackoverflow.com/questions/3806051/accessing-shared$p$pferences-through-static-methods/3806138#3806138

If you search for a static way of how to do it have a look at this: http://stackoverflow.com/questions/3806051/accessing-sharedpreferences-through-static-methods/3806138#3806138

但是IMHO第一溶液将是最好的。

But IMHO the first solution would be the best.

这篇关于安卓:使用共享preferences在图书馆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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