Open In App

Android – Image Picker From Gallery using ActivityResultContracts in Kotlin

Last Updated : 31 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Android has deprecated the startActivityForResult() method and instead of this introduced ActivityResultContracts which is a more efficient way of handling the after-activity result.

Steps to implement image picker from gallery & camera in Kotlin

Enable viewBinding by adding the below code in buide.gradle(app) file inside android {}

Kotlin




viewBinding{
      enabled=true
  }


Getting started with building layout in activity_main.xml

  • The layout of the application includes one Image View to view the selected image and one button to open the image selector.
  • To implement the layout of the application, write the following code in the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
  
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="36dp"
        android:backgroundTint="@color/colorPrimary"
        android:text="SELECT IMAGE"
        android:textColor="@color/white"
        android:textSize="20sp" />
  
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp" />
  
</LinearLayout>


Writing the Kotlin code in the MainActivity Kotlin Class

Kotlin




package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.example.myapplication.databinding.ActivityMainBinding
  
class MainActivity : AppCompatActivity() {
    lateinit var binding:ActivityMainBinding
    val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) {
        val galleryUri = it
        try{
            binding.image.setImageURI(galleryUri)
        }catch(e:Exception){
            e.printStackTrace()
        }
  
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding= ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.button.setOnClickListener {
            galleryLauncher.launch("image/*")
        }
    }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads