getResources() or create own static class?

匿名 (未验证) 提交于 2019-12-03 09:05:37

问题:

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 would 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!

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!