Practical 5 A
Practical 5 A
Aim : To Create an android application kotlin using a grid view layout and insert 6 images of
different animals as the items. Toast the animal name when an image is clicked. (Recycler
View)
Animal.kt package
com.example.imagedashboard
data class
Animal( val name:
String, val
imageResId: Int )
AnimalAdapter.kt package
com.example.imagedashboard
init {
// Set click listener to display the animal's name in a Toast
view.setOnClickListener { val position =
adapterPosition val animal = animalList[position]
Toast.makeText(context, animal.name, Toast.LENGTH_SHORT).show()
}
}
}
item_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:orientation="vertical"
android:gravity="center" android:padding="16dp">
MainActivity.kt
package com.example.imagedashboard
import android.os.Bundle import
androidx.appcompat.app.AppCompatActivity import
androidx.recyclerview.widget.GridLayoutManager import
androidx.recyclerview.widget.RecyclerView class
MainActivity : AppCompatActivity() {
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/> Conclusion :