安卓:访问资源没有活动或上下文refeerence [英] Android: Accessing resources without an Activity or Context refeerence

查看:162
本文介绍了安卓:访问资源没有活动或上下文refeerence的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我张贴,希望我能得到一些明确的答复这个问题。

I am posting this question in the hope that I can get some kind of definitive answer.

难道真的无法访问资源,而无需一个活动或上下文的引用。围绕这些引用传递时所需要的所有的访问某些价值或资产或无关的用户界面使得过于复杂code。字符串

Is it really impossible to access resources without an activity or context reference. Passing around such references when all that is required is to access some values or assets or strings which have nothing to do with the UI makes for overly complicated code.

另外所有这些潜在的悬挂引用。

Plus all those potential hanging references.

另外这完全毁了各种设计模式,如单身,不必提供参数获取实例时。

Also this completely ruins various Design Patterns such as singletons, having to supply parameters when getting the instance.

把静态参考

那么,有没有一种方法还是整个社会只是生活这个问题。

So is there a way or does the whole community just live with this problem.

推荐答案

您的资源捆绑为一个背景下,这是一个事实,你不能改变的。

Your resources are bundled to a context, it's a fact and you can't change that.

下面是你可以做的:

延长应用程序,获取应用程序上下文,并使用它作为一个静态的帮手。

Extend Application, get the application context and use that as a static helper.

public class App extends Application {

    private static Context mContext;

    public static Resources getResources() {
        return mContext.getResources();
    }

    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }
}

您清单:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name="your.package.path.to.App">

这篇关于安卓:访问资源没有活动或上下文refeerence的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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