Android With Kotlin

Android Get Picture from folder set in image view kotlin

01-Jan-2025

Android Get Picture from folder set in image view kotlin

Output:





1/ Modify your activity_main.xml.



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ImageView
android:id="@+id/imgGallery"
android:layout_width="400dp"
android:layout_height="400dp"
android:scaleType="fitXY"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />


<Button
android:id="@+id/btnGallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Gallary"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="@+id/imgGallery"
app:layout_constraintStart_toStartOf="@+id/imgGallery"
app:layout_constraintTop_toBottomOf="@+id/imgGallery" />

</androidx.constraintlayout.widget.ConstraintLayout>



2/Modify your MainActivity.kt



package com.zissofworks.androidgetpicturefromfolder

import android.R.attr
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.IOException


class MainActivity : AppCompatActivity() {

private val GALLERY_REQ_CODE = 100
private lateinit var imgGallery: ImageView
private lateinit var btnGallery: Button

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

imgGallery = findViewById(R.id.imgGallery);
btnGallery = findViewById(R.id.btnGallery);

btnGallery.setOnClickListener {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
type = "image/*"
}
startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY_REQ_CODE)

}
}


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == GALLERY_REQ_CODE && resultCode == RESULT_OK && data != null) {
val imageUri = data.data
imgGallery.setImageURI(imageUri)
}
}

}



Comments