Open File choose in Android app using Kotlin

后端 未结 2 2127
北恋
北恋 2021-02-09 13:44

Task: Upload an image which user can choose from device.

How to open File CHooser window on button press in Android app using Kotlin?

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-09 14:14

    In your activity add the button click to add an intent:

    btnBack.setOnClickListener {
    
        val intent = Intent()
                .setType("*/*")
                .setAction(Intent.ACTION_GET_CONTENT)
    
        startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
    
    }
    

    Set a custom requestCode, I set 111

    Add the onActivityResult in your activity to catch the result:

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    
        if (requestCode == 111 && resultCode == RESULT_OK) {
            val selectedFile = data?.data //The uri with the location of the file
        }
    }
    

    Now selectedFile will contain the location to what they selected.

提交回复
热议问题