activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/android" />
<Button
android:id="@+id/btnChangeImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Image" />
</LinearLayout>
MainActivity.kt
package com.androidian.imageview
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
var button: Button? = null
var image: ImageView? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addListenerOnButton()
}
fun addListenerOnButton() {
image = findViewById(R.id.imageView1)
button = findViewById<View>(R.id.btnChangeImage) as Button
button!!.setOnClickListener { image!!.setImageResource(R.drawable.ic_launcher_background) }
}
}