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>

- android kotlin - ImageView tint programmatically
- android kotlin - ImageView rounded top corners programmatically
- android kotlin - ImageView rounded corners programmatically
- android kotlin - ImageView set image from drawable
- android kotlin - ImageView set image from url
- android kotlin - Get battery capacity programmatically
- android kotlin - Get battery percentage programmatically
- android kotlin - Get battery level programmatically
- android kotlin - Get battery voltage programmatically
- android kotlin - Get battery temperature programmatically
- android kotlin - Get battery health programmatically
- android kotlin - Get battery status programmatically
- android kotlin - On back button pressed example
- android kotlin - Get string resource by name
- android kotlin - Repeat a task periodically