Recently i have started learning Kotlin
. After having some basic functionality i am stuck with image picker.
Does there any specific way to select an image from gallery and camera using Kotlin
? Or should i implement in our normal Java code and then call it from Kotlin
file?
Java code :
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
Any other difference to perform this operation using Kotlin
?
Here a sample function code for selecting image and capture image:
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
}
Also don't forget to add this to your manifest file:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I hope i can help
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)
}
Now that startActivityForResult()
is Deprecated, this is the new way.
First, Do this inside onCreate
Kotlin:
val selectImageIntent = registerForActivityResult(GetContent())
{ uri ->
imageView.setImageURI(uri)
}
Java :
ActivityResultLauncher<String> selectImageIntent = registerForActivityResult(
new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
@Override
public void onActivityResult(Uri uri) {
imageView.setImageURI(uri);
}
});
And call selectImageIntent.launch("image/*")
to launch gallery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With