使用Kotlin从图库中选择图像

时间:2017-05-24 04:14:35

标签: android kotlin

最近我开始学习Kotlin。在拥有一些基本功能后,我被图像选择器困住了。

使用Kotlin是否有任何特定的方式从图库和相机中选择图像?或者我应该在我们的普通Java代码中实现,然后从Kotlin文件中调用它?

Java代码

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

使用Kotlin执行此操作还有其他差异吗?

6 个答案:

答案 0 :(得分:11)

这里是一个用于选择图像和捕获图像的示例功能代码:

 fun selectImageInAlbum() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        if (intent.resolveActivity(packageManager) != null) {
            startActivityForResult(intent, REQUEST_SELECT_IMAGE_IN_ALBUM)
        }
    }
 fun takePhoto() {
        val intent1 = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (intent1.resolveActivity(packageManager) != null) {
            startActivityForResult(intent1, REQUEST_TAKE_PHOTO)
        }
    }
 companion object {
        private val REQUEST_TAKE_PHOTO = 0
        private val REQUEST_SELECT_IMAGE_IN_ALBUM = 1
    }

另外,不要忘记将其添加到您的清单文件中:

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我希望我能帮忙

答案 1 :(得分:3)

val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE)

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    super.onActivityResult(requestCode, resultCode, data)
}

答案 2 :(得分:1)

你也可以在Kotlin写一下。

val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

答案 3 :(得分:1)

您可以尝试以下操作:

val galleryIntent = Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(galleryIntent, requestcode)

答案 4 :(得分:0)

fun Fragment.openGalleryForPickingImage(code: Int) {
    Intent().apply {
        type = "image/*"
        action = Intent.ACTION_GET_CONTENT
        startActivityForResult(Intent.createChooser(this, getString(R.string.select_file)), code)
    }
}

问题在于,获取真实路径的功能不起作用,因为内容解析器找不到对应于MediaStore.Images.Media.DATA的columnIndex 相反,您需要这样做:

fun Fragment.openGalleryForPickingImage(code: Int) {
    Intent(
        Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    ).apply {
        startActivityForResult(Intent.createChooser(this, getString(R.string.select_file)), code)
    }
}

答案 5 :(得分:0)

kotlin:

fun getPhoto() {
    val intent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
    startActivityForResult(intent,1)
}