Android is designed in such a way that in order for a method to read a resource, it must have a access to a Context.
Since most of the classes in my application rely on the flexibility of string resources (e.g. changing language without having to change code, etc.), my simple solution was to pass a Context in their constructor, to provide resource access to each such class.
It doesn’t make sense for me to only pass a string in the constructor, because the class needs the flexibility of access to a varying number of strings.
So, to simplify things, I only pass Context, and whenever a string resource is needed, I just use Context.getString().
Is this a sign of bad design?
Is there a better way to accomplish this?
This is one of the rare occasions where a globally accessible singleton class may be better than passing the
Contextto every single class.I would consider creating a singleton for localization, then use the
Contextinside of there (unless you need other aspects of theContextall over the place).Of course, this is a matter of taste and preference. YMMV