50

私はこのような配列を持っています。

int image[] = {R.drawable.d002_p001,R.drawable.d002_p002,R.drawable.d002_p003,
                   R.drawable.d002_p004,R.drawable.d002_p005,R.drawable.d002_p006};

現在、6 つの画像があるため、静的に名前が付けられています。

50 個の画像がある場合、配列内のすべてのファイル名を指定することはできないため、これをどのように達成できるかを動的にする必要があります。

4

9 に答える 9

115

使用できますgetIdentifier()

for (int j = 1; j < 6; j++) {
   Drawable drawable = getResources().getDrawable(getResources()
                  .getIdentifier("d002_p00"+j, "drawable", getPackageName()));
}
于 2012-02-06T07:32:38.550 に答える
13

これを使用することもできます:

int res = getResources().getIdentifier("<your pakecgename>:drawable/abc", null, null);
于 2012-02-06T08:02:09.413 に答える
7

このようなものが機能する可能性があります

Field[] drawables = android.R.drawable.class.getFields();
for (Field f : drawables) {
    try {
        System.out.println("R.drawable." + f.getName());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
于 2012-02-06T07:23:01.420 に答える
4

動的にドローアブルを取得するには、次の行を使用します。

Drawable drawable = this.getResources().getDrawable(R.drawable.yourDrawableID);

これにより、目的の Drawable が得られます。

于 2012-02-06T07:21:06.773 に答える
2
String[] names = new String []{"yout names..."};
    for(String n: names) {
        Utils.GetDrawableByName(n,this);
    }

public class Utils {
public static Drawable GetDrawableByName(String name,Activity context){
    Resources res = context.getResources();
    return res.getDrawable(res.getIdentifier(name,"drawable",context.getPackageName()));
    }
}
于 2015-09-22T11:05:22.773 に答える
2
public static Drawable getImage(Context context, String name) {
        return context.getResources().getDrawable(context.getResources().getIdentifier(name, "drawable", context.getPackageName()));
}
于 2013-12-24T10:47:08.493 に答える
-10

このコードを使用して配列を作成し、後でその配列を使用します

int NUM_OF_IMAGES = 50;
String images[] = new String[NUM_OF_IMAGES];
for (int i =0; i < NUM_OF_IMAGES; i++) {
    images[i] = "R.drawable.d002_p00" + i;
}

あなたが注意しなければならない主なことは、ファイル名が「d002_p00」で始まり、1から50までの数字があることです

于 2012-02-06T07:16:38.630 に答える