使用单一意图选择图像和Pdf

lok*_*lal 1 android

我知道我们可以使用以下内容

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

那么我们有什么方法可以通过单一意图选择任何单个实体pdf或图像?

Mig*_*cia 14

这里只是一个例子:

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;
}
Run Code Online (Sandbox Code Playgroud)


Hoa*_*Huu 8

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

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
    }
Run Code Online (Sandbox Code Playgroud)

希望可以帮助某人。

  • 您可以通过 `.setType(mimeTypes.joinToString(separator= "|"))` 避免代码重复 (2认同)