【发布时间】:2016-08-11 04:54:07
【问题描述】:
我知道我们可以使用以下
- 挑选图片:intent.setType("image/*");
- 选择 PDF 文件:intent.setType("application/pdf");
那么有什么方法可以让我们通过单一意图选择任何单个实体,无论是 pdf 还是图像?
【问题讨论】:
-
让它成为你想要打开图像的条件,为图像等创造意图..
标签: android
我知道我们可以使用以下
那么有什么方法可以让我们通过单一意图选择任何单个实体,无论是 pdf 还是图像?
【问题讨论】:
标签: android
在我的情况下,上面的答案不起作用,经过一个小时的反复试验,这是我的工作解决方案:
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= "|"))避免代码重复
这里只是一个例子:
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;
}
【讨论】: