如何在 Android 中的文件选择器意图中允许选择 CSV
有一天挣扎之后,我发现该代码“几乎”工作:
private fun showFileChooser() {
val mimeTypes = arrayOf(
"text/csv",
"text/plain",
"application/csv",
"application/vnd.ms-excel",
"application/excel",
"application/x-excel",
"application/x-msexcel"
)
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "text/csv" //if (mimeTypes.size == 1) mimeTypes[0] else "*/*"
if (mimeTypes.isNotEmpty())
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
startActivityForResult(
Intent.createChooser(intent, "choose file"),
MY_RESULT_CODE_FILECHOOSER
)
}
问题是*。csv
无法选择/打开(此是针对另一个问题拍摄的屏幕截图,您可以看到文件出现的方式...它是浅灰色的,就像它是禁用的,实际上无法选择它) 多亏了MIME类型文本/PLAIN
我能够选择*。TXT
文件。
我在Stackoverflow上发现了很多帖子,并提出了不起作用的建议(可能已经不再起作用)。
有什么解决方案吗? 问候
after struggling one day I found this code "almost" works:
private fun showFileChooser() {
val mimeTypes = arrayOf(
"text/csv",
"text/plain",
"application/csv",
"application/vnd.ms-excel",
"application/excel",
"application/x-excel",
"application/x-msexcel"
)
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "text/csv" //if (mimeTypes.size == 1) mimeTypes[0] else "*/*"
if (mimeTypes.isNotEmpty())
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
startActivityForResult(
Intent.createChooser(intent, "choose file"),
MY_RESULT_CODE_FILECHOOSER
)
}
The problem is that *.csv
files cannot be selected/opened (this is a screenshot taken for another issue where you can see how the file appears... it is light gray like it is disable and indeed it cannot be selected)
Thanks to the mime type text/plain
I am able to select *.txt
files.
I found lots of posts here on StackOverflow with suggestions that do not work (probably anymore).
Is there any solution to this?
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
extair_mime_types
时,您需要调用setType(“*/*”)
。请参阅 openfile 常见意图部分。Also, you should consider using the Activity Results API instead of
startActivityForResult ()
,因为它提供了更多类型的安全性,并且后者已弃用。您要寻找的一个是 activationResultContractContracts.getContentss.getContentWhen using
EXTRA_MIME_TYPES
you need to callsetType("*/*")
. See the OpenFile section of Common Intents.Also, you should consider using the Activity Results API instead of
startActivityForResult()
since it provides more type safety and the latter has been deprecated. The one you are looking for is ActivityResultContracts.GetContent