具有特定文件扩展名的Android文件选择器 [英] Android file chooser with specific file extensions

查看:402
本文介绍了具有特定文件扩展名的Android文件选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行默认文件选择器时,我只需要在应用程序中显示"pdf"文件,我就无法过滤文件扩展名.

I need to show only 'pdf' files in my application when I run default File chooser I'm not able to filter file extensions.

    final Intent getContentIntent = new Intent(Intent.ACTION_GET_CONTENT);
    getContentIntent.setType("application/pdf");
    getContentIntent.addCategory(Intent.CATEGORY_OPENABLE);

    Intent intent = Intent.createChooser(getContentIntent, "Select a file");
    startActivityForResult(intent, REQUEST_PDF_GET);

文件选择器显示任何类型的文件.我只想显示pdf文件.如何过滤文件选择器显示的文件.

File chooser shows any kinds of files. I would like to show only pdf files. How can i filter files showed by File chooser.

推荐答案

您不知道您的意图可能触发哪些用户安装的文件浏览器应用程序.我认为在这种情况下,最好用手滚动一些东西.我的方法是

It's an unknown to you what user-installed file browser apps your intent may trigger. I think this is a case where's it's better to hand roll something. My approach was to

a)在外部媒体上查找具有特定扩展名的所有文件,例如(我正在寻找.saf扩展名,因此您将相应地更改为.pdf):

a) Find all files with a particular extension on external media with something like (I was looking for the .saf extension, so you'd alter for .pdf accordingly):

    public ArrayList<String> findSAFs(File dir, ArrayList<String> matchingSAFFileNames) {
    String safPattern = ".saf";

    File listFile[] = dir.listFiles();

    if (listFile != null) {
        for (int i = 0; i < listFile.length; i++) {

            if (listFile[i].isDirectory()) {
                findSAFs(listFile[i], matchingSAFFileNames);
            } else {
              if (listFile[i].getName().endsWith(safPattern)){
                  matchingSAFFileNames.add(dir.toString() + File.separator + listFile[i].getName());
                  //System.out.println("Found one! " + dir.toString() + listFile[i].getName());
              }
            }
        }
    }    
    //System.out.println("Outgoing size: " + matchingSAFFileNames.size());  
    return matchingSAFFileNames;
}

b)将结果放入ListView,然后让用户触摸他/他想要的文件.您可以根据需要将列表设置为精美-显示缩略图,文件名等.

b) Get that result into a ListView and let the user touch the file s/he wants. You can make the list as fancy as you want -- show thumbnails, plus filename, etc.

听起来好像要花很长时间,但实际上并不需要,然后您就知道每个设备的行为.

It sounds like it would take a long time, but it didn't and you then know the behavior for every device.

这篇关于具有特定文件扩展名的Android文件选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆