Android – Image Picker From Gallery using ActivityResultContracts in Kotlin
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
- Create an empty activity Android project, select Kotlin as the language, and click finish.
- Refer to How to Create/Start a New Project in Android Studio to know how to create an empty activity Android Studio Project.
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:android = "http://schemas.android.com/apk/res/android" 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/*" ) } } } |