dynamically getting all image resource id in an array

前端 未结 2 2013
陌清茗
陌清茗 2020-12-09 11:52

there are many images in drawable foder so instead manually creating array of all image resource ids , i want to get all images dynamically of drawable folder in array. cur

相关标签:
2条回答
  • 2020-12-09 11:55

    Well, If your image names are img1, img2 and so on, then you can create a variable like

    String url = "drawable/"+"img"+i;
    
    int imageKey = getResources().getIdentifier(url, "drawable", getPackageName());
    

    you can also replace your getPackageName() method by your package name like "com.android.resource"
    Simply,the general function is

    public int getIdentifier(String name, String defType, String defPackage)
    
    0 讨论(0)
  • 2020-12-09 11:56

    you can Use Reflection to achieve this.

    import the Field class

    import java.lang.reflect.Field;

    and then write this in your code

    Field[] ID_Fields = R.drawable.class.getFields();
    int[] resArray = new int[ID_Fields.length];
    for(int i = 0; i < ID_Fields.length; i++) {
        try {
            resArray[i] = ID_Fields[i].getInt(null);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    resArray[] now holds references to all the drawables in your application.

    0 讨论(0)
提交回复
热议问题