After a while, you really do get sick of passing Context and Activity arguments around just so you can pull resources from your package.
It makes your code messy, unnecessarily clutters up function signatures and is a general pain in the ass.
Well, looks like this problem was solved long ago and I should have looked into it earlier!
- The first thing you need to do is extend the Application class.
- Override onCreate() so you can store a static reference to the application context.
- Create a static function getResourcesStatic() to use it, since getResources() already exists and is non-static.
01.
public
class
MyApplication
extends
Application {
02.
private
static
Context context;
03.
04.
public
static
Resources getResourcesStatic() {
05.
return
context.getResources();
06.
}
07.
08.
@Override
09.
public
void
onCreate() {
10.
super
.onCreate();
11.
12.
this
.context = getApplicationContext();
13.
}
14.
}
- Lastly, change your AndroidManifest.xml file to use the new Application class.
1.
<
application
2.
android:icon
=
"@drawable/ic_launcher"
3.
android:label
=
"@string/app_name"
4.
<strong>android:name="MyApplication"</
strong
>>
And that's it!
From now on, you can remove all those context arguments and replace them with MyClass.getResourcesStatic()
Exciting stuff, no?
Source