numberwang
numberwang

Reputation: 313

Get a list of filenames in a drawable resource directory

I want to get a list of certain filenames in a drawable resource directory (at runtime, not using XML). I guess, I would need to distinguish certain files from others. So ...
*res/drawable-hdpi/mysubdir
-- x-one.png
-- one.png
-- x-two.png
-- two.png
-- x-three.png
-- three.png *

I want to put the x-*.png filenames into a List<String>. Is this possible? Borrowing some code from another question, I can get all the drawables, but I don't see a way to distinguish one from another in a meaningful way.

private void getDrawableResources() {

final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> drawableClass = R.drawable.class;
final Field[] fields = drawableClass.getDeclaredFields();
final List<Integer> resourceIdList = new ArrayList<Integer>();

for (int i = 0, max = fields.length; i < max; i++) {
    final int resourceId;
    try {
        resourceId = fields[i].getInt(drawableResources);
        resourceIdList.add(resourceId);
    } 
    catch (Exception e) {
        continue;
    }
}

Resources resources = this.getActivity().getResources();
for (int i = 0; i < resourceIdList.size(); i++) {
        Drawable drawable = resources.getDrawable(resourceIdList.get(i));
        resourceIdList.get(i) + "): " +  drawable.toString());
}
}

Upvotes: 0

Views: 1715

Answers (2)

AndRSoid
AndRSoid

Reputation: 1825

Use FileNameFilter while getting list of files in a directory.

      File dir = new File(dirLocation);

      if(dir.exists() && dir.isDirectory())
        {
            File[] files = dir.listFiles(new FilenameFilter()
            {
                public boolean accept(File dir, String name)
                {
                    return name.contains("X-");
                }
            });
        }

Upvotes: 1

ianhanniballake
ianhanniballake

Reputation: 200120

Resource directories do not support subdirectories.

Upvotes: 1

Related Questions