Android动态地将图像(标题)从drawable加载到Array List

问题描述 投票:0回答:3

我的可绘制文件夹中有超过1000个图像,我需要将所有这些图像加载到数组列表中,以便稍后在程序运行时进行搜索。在android中是否有任何可能的方法可以动态加载ArrayList中的所有图像?

谢谢

java android
3个回答
3
投票

这段代码由我工作和测试,您可以从drawable获取所有图像并将其保存在ArrayList中。

但在我看来,这是一个非常糟糕的主意

码:

 ArrayList<Integer> arrayOfIcons = new ArrayList<>();

Field[] drawables = R.drawable.class.getFields();
for (Field f : drawables) {
    try {
        int resID = getResources().getIdentifier(f.getName() , "drawable", getPackageName());
        arrayOfIcons.add(resID);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

ImageView imageView = findViewById(R.id.imageView);
imageView.setImageResource(arrayOfIcons.get(0));

我希望它对你有所帮助。


0
投票

import java.lang.reflect.Field;

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();
    }
}

0
投票

这是最终的工作代码:

 ImageView imageView = findViewById(R.id.testImage);
    //load all the icon names from drawable
    ArrayList<String> arrayOfIcons = new ArrayList<>();

    //load the array containing specific characters
    containingArray = new ArrayList<>();

    Field[] drawables = R.drawable.class.getFields();
    for (Field f : drawables) {
        try {
            int resID = getResources().getIdentifier(f.getName() , "drawable", getPackageName());
            arrayOfIcons.add(f.getName());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //search for all similar keywords
    for(int i =0; i < arrayOfIcons.size();i++){
        if(arrayOfIcons.get(i).contains(title_string) && arrayOfIcons.get(i).contains("_")){
            containingArray.add(arrayOfIcons.get(i));
        }
    }
    //split array
    for(int i = 0; i < containingArray.size();i++){

        //finding the index that contains the keyword 
        if(containingArray.get(i).substring(0,containingArray.get(i).lastIndexOf("_")).equalsIgnoreCase(title_string)){
            Context context = imageView.getContext();
            int id = context.getResources().getIdentifier(containingArray.get(i), "drawable", context.getPackageName());
            imageView.setImageResource(id);
        }
        System.out.println("ContainingArray: "+containingArray.get(i));
    }
© www.soinside.com 2019 - 2024. All rights reserved.