我只想从存储中选择 pdf、xlsx 和 txt 文件,但 intent.setType 只能执行一个文件(例如,仅 .txt 文件(或)仅 pdf 文件)。是否可以通过编码intent.setType()来获取所有三个文件,有没有办法?
这是我的一些代码。
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select txt file"),
0);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
}
}
最佳答案
@Fatehali Asamadi 的方式还可以,但需要添加一些东西以供适当使用。 对于 Microsoft 文档(.doc 或 .docx)、(.ppt 或 .pptx)、(.xls 或 .xlsx)扩展名都使用。要支持或浏览这些扩展,您需要添加更多 mimeType。
使用以下方法浏览文档,其中 REQUEST_CODE_DOC 为 onActivityResult(final int requestCode, final int resultCode,final Intent data) @Override 方法的 requestCode。
private void browseDocuments(){
String[] mimeTypes =
{"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
"application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
"application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
"text/plain",
"application/pdf",
"application/zip"};
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));
}
startActivityForResult(Intent.createChooser(intent,"ChooseFile"), REQUEST_CODE_DOC);
}
您可以从 Here 获得清晰的概念并添加所需的 mimeTypes
关于android - 如何为 pdf、xlsx 和 txt 文件制作intent.setType android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978581/