将多个 Mime 类型传递给 ActivityResultLauncher.launch()

Nik*_*kki 5 mime-types kotlin onactivityresult registerforactivityresult

我有以下代码

val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
    //Some code here..
}
Run Code Online (Sandbox Code Playgroud)

和其他地方,

getContent.launch("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
Run Code Online (Sandbox Code Playgroud)

我可以成功选择 docx 文件。我需要选择 pdf 或 doc 或 text 或 docx 而只是能够选择一种(此处为 docx)。

Hus*_*ain 6

我建议使用OpenDocument而不是GetContent.

val documentPick =
    registerForActivityResult(ActivityResultContracts.OpenDocument()) { result ->
        // do something 
    }
Run Code Online (Sandbox Code Playgroud)

在启动意图时,只需添加您想要获得的 mime 类型

documentPick.launch(
            arrayOf(
                "application/pdf",
                "application/msword",
                "application/ms-doc",
                "application/doc",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "text/plain"
            )
        )
Run Code Online (Sandbox Code Playgroud)

  • 您在哪里找到有关如何将“arrayOf()”参数传递给“launch”的文档?我一直在文档中搜索这种语法,但似乎找不到任何接近的东西。 (3认同)

小智 5

使用数组在我的情况下不起作用。相反,以下工作正常。这里使用了 ActivityResultContracts.GetContent 的自定义类。fun“createIntent”被重写以自定义方法以从输入中获取意图。

    // custom class of GetContent: input string has multiple mime types divided by ";"
    // Here multiple mime type are divided and stored in array to pass to putExtra.
    // super.createIntent creates ordinary intent, then add the extra. 
    class GetContentWithMultiFilter:ActivityResultContracts.GetContent() {
        override fun createIntent(context:Context, input:String):Intent {
            val inputArray = input.split(";").toTypedArray()
            val myIntent = super.createIntent(context, "*/*")
            myIntent.putExtra(Intent.EXTRA_MIME_TYPES, inputArray)
            return myIntent
        }
    }

    // define ActivityResultLauncher to launch : using custom GetContent
    val getContent=registerForActivityResult(GetContentWithMultiFilter()){uri ->
    ... // do something
    }

    // launch it
    // multiple mime types are separated by ";".
    val inputString="audio/mpeg;audio/x-wav;audio/wav"
    getContent.launch(inputString)
Run Code Online (Sandbox Code Playgroud)