I want to read strings from an xml
file before I do much of anything else like setText
on widgets, so how can I do that without an activity object to call getResources()
on?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How can I create this custom Bottom Navigation on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
Use
You can use them everywhere in your application, even in static constants declarations! But for system resources only!
In your class, where you implement the static function, you can call a private\public method from this class. The private\public method can access the getResources.
for example:
and from other class\activity, you can call:
I like shortcuts.
I use
App.getRes()
instead ofApp.getContext().getResources()
(as @Cristian answered)What? It is very simple to use anywhere in your app!
So here is a unique solution by which you can access resources from anywhere like
Util class
.(1) Create or Edit your
Application
class.(2) Add name field to your
manifest.xml
<application
tag. (or Skip this if already there)Now you are good to go. Use
App.getRes().getString(R.string.some_id)
anywhere in app.The Singleton:
Initialize the Singleton in your
Application
subclass:If I´m not wrong, this gives you a hook to applicationContext everywhere, call it with
ApplicationContextSingleton.getInstance.getApplicationContext();
You shouldn´t need to clear this at any point, as when application closes, this goes with it anyway.Remember to update
AndroidManifest.xml
to use thisApplication
subclass:Now you should be able to use ApplicationContextSingleton.getInstance().getApplicationContext().getResources() from anywhere, also the very few places where application subclasses can´t.
Please let me know if you see anything wrong here, thank you. :)
Application
, for instancepublic class App extends Application {
android:name
attribute of your<application>
tag in theAndroidManifest.xml
to point to your new class, e.g.android:name=".App"
onCreate()
method of your app instance, save your context (e.g.this
) to a static field namedmContext
and create a static method that returns this field, e.g.getContext()
:This is how it should look:
Now you can use:
App.getContext()
whenever you want to get a context, and thengetResources()
(orApp.getContext().getResources()
).