Android: Accessing resources without an Activity or Context refeerence
I a开发者_C百科m posting this question in the hope that I can get some kind of definitive answer.
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.
Putting a static reference
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.
Here's what you can do:
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();
}
}
Your manifest:
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:name="your.package.path.to.App">
Make your Application
class a singleton and use that. It is a Context
. All resources are tied to your app, so you need a Context
reference. You can pre-load strings, etc. in a singleton class if you don't want to load them dynamically.
I guess you could use context from some UI element like textView.getContext() if the other responses don't work for you.
精彩评论