2016-09-15 39 views
1

我正在循环一些可绘制的图像(fx。我有一些名为image_1,image_2等的图像)作为片段中的标题图像。随着硬编码可用于我的图像数量,图像随机加载,并生成一个从0到这个数字的随机索引。Android:计数字符串和绘图

mHeaderBackgroundImagesCount是最后:

private int getHeaderBackground() { 
    // Random index between 0 and mHeaderBackgroundImagesCount 
    Random rand = new Random(); 
    int index = rand.nextInt(mHeaderBackgroundImagesCount) + 1; 

    return getResources() 
      .getIdentifier("image_" + index, "drawable", getPackageName()); 
} 

由于硬编码什么是不正常的正确程序要走的路,所以我喜欢动态的了解有多少“image_X”可绘有与设置到mHeaderBackgroundImagesCount

我想对来自strings.xml资源文件的字符串做同样的操作,因为我还在每个页面加载中传递一些字符串。

解决方案更新

此更新通过拉利特Poptani的下面建议的启发。它包括语法更正和优化,并且已经过测试。

private int countResources(String prefix, String type) { 
    long id = -1; 
    int count = -1; 
    while (id != 0) { 
     count++; 
     id = getResources().getIdentifier(prefix + (count + 1), 
       type, getPackageName()); 
    } 

    return count; 
} 

System.out.println("Drawables counted: " + countResources("image_", "drawable")); 
System.out.println("Strings counted: " + countResources("strTitle_", "string")); 

注意:此方法假设资源计数开始具有索引1和不具有索引孔像image_1image_2<hole>image_4等等,因为它会终止ID的第一时刻= 0因此导致有缺陷的计数。

回答

1

如果您确信您可绘制的名单将在IMAGE_1,IMAGE_2,序列......等等,那么你可以申请以下逻辑,

 int count = 0; 
     int RANDOM_COUNT = 10; //which is more than your drawable count 
     for (int i = 1; i < RANDOM_COUNT; i++){ 
      int id = getResources().getIdentifier("ic_launcher_"+i, 
                "drawable", getPackageName()); 
      if(id != 0){ 
       count = + count; 
      } 
      else{ 
       break; 
      } 
     } 
     Log.e(TAG, "This is your final count of drawable with image_x - "+ count); 

您可以使用此逻辑因为将不会有任何可绘制的名称image_x然后id将为0,你可以打破循环

+0

我已经在上面的原始文章中发布了一个修订的过程,它避免了对RANDOM_COUNT的需求。 – Ambran

+0

@Ambran听起来不错,所以最后选择了哪种方法最终在你的代码中使用? –

+0

我已经使用了我上面发布的修订版本,因为使用'while'循环无需声明某个天花板(RANDOM_COUNT)索引,就像'for'循环所需的索引一样。这个想法是一样的,所以非常感谢。 – Ambran

1

我不确定是否可以动态获取资源或可绘制的数量。

解决此问题的一种方法是使用字符串数组作为strings.xml中的资源。

例如

<resources> 
<string-array name="foo_array"> 
    <item>abc1</item> 
    <item>abc2</item> 
    <item>abc3</item> 
</string-array> 

int count = getResources().getStringArray(R.array.foo_array).length; 
+0

很酷,很高兴我能帮上忙。 – qantik