【问题标题】:Pick Image and Pdf using single intent使用单一意图选择图像和 Pdf
【发布时间】:2016-08-11 04:54:07
【问题描述】:

我知道我们可以使用以下

  1. 挑选图片:intent.setType("image/*");
  2. 选择 PDF 文件:intent.setType("application/pdf");

那么有什么方法可以让我们通过单一意图选择任何单个实体,无论是 pdf 还是图像?

【问题讨论】:

标签: android


【解决方案1】:

在我的情况下,上面的答案不起作用,经过一个小时的反复试验,这是我的工作解决方案:

fun getFileChooserIntentForImageAndPdf(): Intent {
        val mimeTypes = arrayOf("image/*", "application/pdf")
        val intent = Intent(Intent.ACTION_GET_CONTENT)
                .setType("image/*|application/pdf")
                .putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
        return intent
    }

希望可以帮助别人。

【讨论】:

  • 太棒了,它有效,非常感谢,你救了我
  • 您可以通过.setType(mimeTypes.joinToString(separator= "|"))避免代码重复
【解决方案2】:

这里只是一个例子:

private Intent getFileChooserIntent() {
    String[] mimeTypes = {"image/*", "application/pdf"};

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
        if (mimeTypes.length > 0) {
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        }
    } else {
        String mimeTypesStr = "";

        for (String mimeType : mimeTypes) {
            mimeTypesStr += mimeType + "|";
        }

        intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
    }

    return intent;
}

【讨论】:

  • 不知道为什么不被接受。其实是正确的答案。
  • 执行我,但我知道所选文件的类型,是 pdf 还是图像?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
相关资源
最近更新 更多