startActivityForResult Depreciated Solution | Android Studio | Kotlin
How to use ActivityResult OR ActivityResultLauncher?
Since the startActivityForResult() used to launce the intents like Gallery, Camera, File Pick, Share data, etc is deprecated so now there is a new way to do that ActivityResultLauncher class.
Video Tutorial:
Code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <!--ImageView: Set image after picking from gallery--> <ImageView android:id="@+id/profileIv" android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/ic_image_black" android:adjustViewBounds="true"/> <!--Button: launch intent to pick image from gallery--> <Button android:id="@+id/intentBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pick Image"/> </LinearLayout>
MainActivity.kt
package com.technifysoft.activityresultkotlin import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts class MainActivity : AppCompatActivity() { private lateinit var profileIv:ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //UI Views (use ViewBinding instead of findViewById - recommended) profileIv = findViewById(R.id.profileIv) val intentBtn:Button = findViewById(R.id.intentBtn) //handle click, launch gallery intent to pick image intentBtn.setOnClickListener { //intent to launch gallery val intent = Intent(Intent.ACTION_PICK) //set type intent.type = "image/*" galleryActivityResultLauncher.launch(intent) } } private val galleryActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result -> //handle intent result here if (result.resultCode == Activity.RESULT_OK){ //image picked //get uri of image picked val data = result.data val imageUri = data!!.data //set image to imageview profileIv.setImageURI(imageUri) } else{ //cancelled Toast.makeText(this@MainActivity, "Cancelled", Toast.LENGTH_SHORT).show() } } }
Comments
Post a Comment