【问题标题】:Get a list of filenames in a drawable resource directory获取可绘制资源目录中的文件名列表
【发布时间】:2014-01-04 04:07:17
【问题描述】:

我想在可绘制资源目录中获取某些文件名的列表(在运行时,不使用 XML)。我想,我需要将某些文件与其他文件区分开来。所以...
*res/drawable-hdpi/mysubdir
-- x-one.png
-- one.png
-- x-two.png
-- 两个.png
-- x-three.png
-- 三.png *

我想将x-*.png 文件名放入List<String>。这可能吗? 借用另一个问题的一些代码,我可以得到所有的可绘制对象,但我看不到一种以有意义的方式区分彼此的方法。

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

【问题讨论】:

    标签: android android-resources android-drawable


    【解决方案1】:

    资源目录不支持子目录。

    【讨论】:

    • 那个问题一直在我的脑海里。我忽略了它。我将相应地编辑问题。
    【解决方案2】:

    在获取目录中的文件列表时使用 FileNameFilter。

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2012-04-23
    • 2017-02-24
    • 2020-05-04
    • 1970-01-01
    • 2011-04-24
    相关资源
    最近更新 更多