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.
public class MyApplication extends Application {
private static Context context;
public static Resources getResourcesStatic() {
return context.getResources();
}
@Override
public void onCreate() {
super.onCreate();
this.context = getApplicationContext();
}
}
- Lastly, change your AndroidManifest.xml file to use the new Application class.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name="MyApplication">
And that's it!
From now on, you can remove all those context arguments and replace them with MyClass.getResourcesStatic()