【问题标题】:Calling getResources() ten times Android调用 getResources() 十次 Android
【发布时间】:2014-09-14 13:30:20
【问题描述】:

正如我的问题所说,我需要使用 getResources() 获取十个不同的字符串,然后将它们与用户输入的字符串进行比较。
这就是我目前的做法:

if(string == getResources().getString(R.string.x)) 

由于此代码将在 R.java 中针对十个不同的字符串重复十次,我想知道调用 getResources() 这么多次是否会降低性能。

有没有更简单的解决方案,比如从 getResources() 创建一个对象,然后从该对象一次获取一个字符串?

对不起,如果我在喋喋不休,我是新手。

谢谢!

【问题讨论】:

  • string == ...祝你好运...无论如何c2.com/cgi/wiki?PrematureOptimization
  • 如果您很担心,只需分配一次:final Resources resources = getResources()。同样对于字符串,您必须使用 equals 而不是 ==

标签: android string getresource


【解决方案1】:

然后你可以这样做:

Resources res = yourContext.getResources();
//use this res variable instead of getResources() function a small example
Bitmap bitmap = BitmapFactory.decodeResource(res,R.id.ic_launcher);

【讨论】:

  • 谢谢!这就是我想要的答案……有点。只是一个想法,假设我在 onCreate() 方法中,我可以输入“this”代替 yourContext,还是需要指定它,如“MainActivity.this”?
【解决方案2】:

另一种方法是将您获得的字符串添加为string-array

<string-array name="string_array_name">
    <item>text_string</item>
    <item>text_string</item>
</string-array>

得到你的数组:

String[] myArr = getResources().getStringArray(R.array.string_array_name);

然后循环遍历它们......你会打电话给getResources()一次......

但无论如何,资源对象是整个应用程序中的共享对象,您只是将其称为吸气剂,因此没有性能问题

【讨论】:

    【解决方案3】:

    你可以在string.xml创建一个数组

    字符串.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string-array name="item_array">
            <item>item 1</item>
            <item>item 2</item>
            <item>item 3</item>
            <item>item 4</item>
    ...
        </string-array>
    </resources>
    

    在你的 java 代码中你可以访问它

    String[] mTestArray =   getResources().getStringArray(R.array. item_array);
    

    【讨论】:

      【解决方案4】:

      为避免getResources()重复调用,在Resources类型的变量之前创建,并使用它代替调用,如下:

      Resources res = getResources();
      if (string == res.getString(R.string.x);
      

      通过这种方式,您还可以将变量作为参数传递给其他方法/函数,在所有代码中只调用一次getResources()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-31
        • 1970-01-01
        • 2023-02-01
        • 1970-01-01
        • 2023-03-17
        • 2012-11-23
        • 2011-12-11
        相关资源
        最近更新 更多