简体   繁体   English

Android 如何迭代一个 R.drawable 对象

[英]Android How to iterate an R.drawable object

I'm trying to display a frame by frame animation and want to iterate through the drawables so I don't have to type all their names in case the number of frames increases.我正在尝试逐帧显示动画并希望遍历可绘制对象,因此我不必输入它们的所有名称,以防帧数增加。

However I can't seem to find how to iterate through the drawables.但是我似乎无法找到如何遍历可绘制对象。 I have looked up a fair bit of java for loop tutorials but they all just printed stuff which (as far as I'm sure) don't have to use here.我已经查找了相当多的 java for 循环教程,但它们都只是打印了(据我所知)不必在这里使用的东西。

Here's the relevant code (the image's names are dude1, dude2, ...):这是相关的代码(图像的名称是 dude1、dude2、...):

   private void startAnimation(){
       animation = new AnimationDrawable();
       for (int i = 1; i < 4; i++) {
           animation.addFrame(getResources().getDrawable(R.drawable.dude(i)), 100);
       }
       animation.setOneShot(true);

       ImageView imageView = (ImageView) findViewById(R.id.img);
       RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(80, 90);
       params.alignWithParent = true;
       params.addRule(RelativeLayout.CENTER_IN_PARENT);      
       imageView.setLayoutParams(params);
       imageView.setImageDrawable(animation);
       imageView.post(new Starter());
   }

Thx!谢谢!

I think the last answer is varely true but it may be:我认为最后一个答案是正确的,但可能是:

for (int i=0; i <10;i++){
      animation.addFrame(
         getResources().getDrawable(getResources().getIdentifier("dude" + i,"drawable",
             getPackageName()),100);
}

Try this.试试这个。 getResources() needs a context. getResources()需要一个上下文。

for (int i=0;i<10;i++){
    animation.addFrame(getResources().getIdentifier("dude" + i,"drawable", getPackageName()),100);
}

Here, I have assumed 10 frames (i<10).在这里,我假设了 10 帧(i<10)。

I have used Simon 's answer to iterate through my drawables that are named "c1" through "c54" and placed in an array.我已经使用Simon的答案来迭代我的可绘制对象,这些对象名为“c1”到“c54”并放置在一个数组中。 Here is the code I just used that works for me.这是我刚刚使用的对我有用的代码。

 private void getDeckDrawables() {
    for (int i=1; i<53; i++){
        intArrDeck[i-1] = getResources().getIdentifier("c"+i,"drawable",getPackageName());
    }
}

Previously, I typed them manually which took up too much room for my taste.以前,我手动输入它们,这占用了我的口味太多空间。

private void getDeckDrawables() {
    intArrDeck[0]=R.drawable.c1;
    intArrDeck[1]=R.drawable.c2;
    intArrDeck[2]=R.drawable.c3;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM