Tuesday, August 18, 2020

android kotlin - ImageView set image from Uri

MainActivity.kt

package com.example.jetpack

import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get uri from drawable
        val uri = applicationContext.drawableToUri(R.drawable.tulip)

        // remove previous image uri cache
        imageView.setImageURI(null)

        // set image view image from uri
        imageView.setImageURI(uri)

        // show the uri in text view
        textView.text = uri.toString()
    }
}


// extension function to get uri from drawable
fun Context.drawableToUri(drawable: Int):Uri{
    return Uri.parse("android.resource://$packageName/$drawable")
}
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/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="300dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#0014A8"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>