Android ImageView-Button Kotlin Tutorial –ImageView-Button Kotlin Example

Tutorial:

Step 1:
Open up Android Studio Project through res -> layout -> activity_main.xml (or) main.xml and add below code or just drag and drop the switch to design XML file

 
<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:tint="@color/colorPrimary"
        android:id="@+id/iv_image_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="8dp"
        android:src="@color/colorPrimary"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </ImageView>

    <Button
        android:id="@+id/bt_change"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:text="Change"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent">

    </Button>



</androidx.constraintlayout.widget.ConstraintLayout>

Step 2:

Add below code in MainActivity.kt.I have added ic_android_black_24dp from right click on drawable and select VectorAssets and add ic_android_black_24dp.

import android.view.View
import com.bytelogs.example.R
import kotlinx.android.synthetic.main.activity_main.*
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity(),View.OnClickListener{

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

    override fun onClick(view: View?) {
        val id = view?.id;
        when(id){
            R.id.bt_change -> onClickChange()
        }
    }
    private fun onClickChange(){
        iv_image_view.setImageResource(R.drawable.ic_android_black_24dp)
    }
}

.