Android: access to resources without reassessing activity or context

I am posting this question in the hope that I will get some final answer.

Is it really impossible to access resources without reference to an action or context. Moving around such links when all that is required is access to some values ​​or assets or strings that have nothing to do with the user interface, which makes for overly complex code.

Plus all of these potential dangling links.

In addition, it completely destroys various design patterns, such as single games, which must supply parameters when an instance is received.

Setting a static link

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

+7
source share
2 answers

Your resources are context-bound; this is a fact, and you cannot change it.

Here is what you can do:

Extend Application , get application context and use it 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(); } } 

Your manifest:

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

Make your Application class single and use it. This is Context . All resources are tied to your application, so you need a Context link. You can preload lines, etc. In a singleton class, if you do not want to load them dynamically.

0
source

All Articles