开发者

getResources() or create own static class?

I noticed myself constantly typing:

someVar = getResources().getString(R.string.someString);

I have several XML files that I am parsing and building and in order to make sure that the files stay consistent, I have placed the tag names in the res/values/strings.xml file. The same handles are used throughout several activities, and some of those activities extend ListActivity while others do not so creating a simple super class which houses these variables ( ex:

public class thisClass extends thatClass 
{...}

public class thatClass 
{
    package String someTag = "this";
    package String otherTag = "that"; 
}

I wo开发者_如何学Pythonuld assume that all of these calls to getResources() could get pretty taxing and was wondering if it is beneficial to instead create an R-type file where I can store these types of commonly used variables statically ex:

public final class globalVars 
{
    public static final class XML_TAGS 
    {
        static final String someTag = "this";
        static final String otherTag = "that";
    }
}

and to reference these variables like such:

serializer.startTag("", globalVars.XML_TAGS.someTag);

instead of

serializer.startTag("", getResources().getString(R.string.someTag));

Thanks for the input!


OK, after looking into the source code of android.content.res.resources and some other classes, it is evident that using Resources and getting resources through getResources() is costly compared to a static class.

Indeed, the instance of Resources returned is not a static container but rather an object that gets resources by executing a couple of statements (whether a string or drawable or any other form).

However, using getResources() has its advantages:

  • It helps you externalize your resources.
  • For any type of resource, you can specify default and multiple alternative resources depending maybe on Locale, Screen Depth/Resolution...

A static container might provide a less costly alternative than using resources but remember: any later attempt at localization would be relatively extremely costly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜