0% found this document useful (0 votes)
0 views

Android

The document contains code for multiple Android applications demonstrating various functionalities. It includes a GridView example displaying items with images, a Radio Button example for user input, a Canvas drawing application, and a Calculator application for basic arithmetic operations. Each practical includes Kotlin code, XML layout files, and user interaction features.

Uploaded by

Suraj Chauhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Android

The document contains code for multiple Android applications demonstrating various functionalities. It includes a GridView example displaying items with images, a Radio Button example for user input, a Canvas drawing application, and a Calculator application for basic arithmetic operations. Each practical includes Kotlin code, XML layout files, and user interaction features.

Uploaded by

Suraj Chauhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 144

Practical 1 ( Gridviewexample )

Main.kt

package com.example.gridviewexample

import android.os.Bundle
import android.widget.GridView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val gridView: GridView = findViewById(R.id.gridView)

// Create the list of items with titles and image resource IDs
var courseList = listOf<GridViewModal>()
courseList = courseList + GridViewModal("Tshirts", R.drawable.tshirts)
courseList = courseList + GridViewModal("Cap", R.drawable.cap)
courseList = courseList + GridViewModal("Shoes", R.drawable.shoes)
courseList = courseList + GridViewModal("Python", R.drawable.python)
courseList = courseList + GridViewModal("Javascript", R.drawable.js)

// Set up the adapter with the course list


val adapter = GridViewAdapter(this, courseList)
gridView.adapter = adapter
}
}

Adapter.kt

package com.example.gridviewexample

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView

data class GridViewModal(val title: String, val imageResId: Int)

class GridViewAdapter(private val context: Context, private val items: List<GridViewModal>) :


BaseAdapter() {

override fun getCount(): Int = items.size

override fun getItem(position: Int): Any = items[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val view: View = convertView ?: LayoutInflater.from(context).inflate(R.layout.grid_item, parent,
false)

// Bind image and title to the layout


val imageView: ImageView = view.findViewById(R.id.imageView)
val textView: TextView = view.findViewById(R.id.textView)

val item = items[position]


imageView.setImageResource(item.imageResId)
textView.text = item.title

return view
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" />
</RelativeLayout>

Grid.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="5dp">

<ImageView
android:id="@+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="centerCrop" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textColor="#000"
android:textSize="14sp"
android:gravity="center" />
</LinearLayout>

Practical 2 ( Radio Buttons )


Main.kt

package com.example.androidpractical2

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Input and Show Button


val editText = findViewById<EditText>(R.id.editText)
val buttonShowInput = findViewById<Button>(R.id.buttonShowInput)
buttonShowInput.setOnClickListener {
val inputText = editText.text.toString()
Toast.makeText(this, inputText, Toast.LENGTH_SHORT).show()
}

// RadioGroup and Get Color Button


val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
val buttonGetColor = findViewById<Button>(R.id.buttonGetColor)
buttonGetColor.setOnClickListener {
val selectedRadioId = radioGroup.checkedRadioButtonId
if (selectedRadioId != -1) {
val selectedRadioButton = findViewById<RadioButton>(selectedRadioId)
Toast.makeText(this, "Selected: ${selectedRadioButton.text}", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Please select a color", Toast.LENGTH_SHORT).show()
}
}

// Checkbox Button
val checkBoxCS = findViewById<CheckBox>(R.id.checkBoxCS)
val checkBoxIT = findViewById<CheckBox>(R.id.checkBoxIT)
val buttonSubmit = findViewById<Button>(R.id.buttonSubmit)
buttonSubmit.setOnClickListener {
val selectedOptions = mutableListOf<String>()
if (checkBoxCS.isChecked) selectedOptions.add("CS")
if (checkBoxIT.isChecked) selectedOptions.add("IT")
Toast.makeText(this, "Selected: ${selectedOptions.joinToString(", ")}",
Toast.LENGTH_SHORT).show()
}

// Spinner
val spinnerLanguage = findViewById<Spinner>(R.id.spinnerLanguage)
val languages = arrayOf("Java", "Kotlin", "C++", "Python")
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerLanguage.adapter = adapter

spinnerLanguage.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {


override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Toast.makeText(this@MainActivity, "Selected: ${languages[position]}",
Toast.LENGTH_SHORT).show()
}

override fun onNothingSelected(parent: AdapterView<*>?) {


// Do nothing
}
}
}
}

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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Input"
android:layout_margin="16dp"
android:inputType="text"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonShowInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Show Input"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/editText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonShowInput">

<TextView
android:id="@+id/radioGroupTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Which is your favorite color?"
android:textStyle="bold"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioYellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yellow"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioPink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pink"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioGreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green"
android:textColor="@android:color/white" />
</RadioGroup>

<Button
android:id="@+id/buttonGetColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Color"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toStartOf="@id/radioGroup"
app:layout_constraintTop_toBottomOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewDemo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView Demo"
android:textColor="@android:color/white"
app:layout_constraintTop_toTopOf="@id/radioGroup"
app:layout_constraintStart_toEndOf="@id/radioGroup"
app:layout_constraintEnd_toEndOf="parent" />

<CheckBox
android:id="@+id/checkBoxCS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CS"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/textViewDemo"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<CheckBox
android:id="@+id/checkBoxIT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IT"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/checkBoxCS"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/checkBoxIT"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Language"
android:textColor="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />

<Spinner
android:id="@+id/spinnerLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toEndOf="@id/textViewLanguage"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />
</androidx.constraintlayout.widget.ConstraintLayout>

Practical 3 ( Canva )
Main.kt

package com.example.canvas
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
class MainActivity : AppCompatActivity(), View.OnTouchListener {
// Declaring ImageView, Bitmap, Canvas, Paint,
// Down Coordinates and Up Coordinates
private lateinit var mImageView: ImageView
private lateinit var bitmap: Bitmap
private lateinit var canvas: Canvas
private lateinit var paint: Paint
private var downX = 0f
private var downY = 0f
private var upX = 0f
private var upY = 0f
@RequiresApi(Build.VERSION_CODES.R)
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initializing the ImageView
mImageView = findViewById(R.id.image_view_1)
// Getting the current window dimensions
val currentDisplay = windowManager.currentWindowMetrics
val dw = currentDisplay.bounds.width()
val dh = currentDisplay.bounds.height()
// Creating a bitmap with fetched dimensions
bitmap = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888)
// Storing the canvas on the bitmap
canvas = Canvas(bitmap)
// Initializing Paint to determine
// stoke attributes like color and size
paint = Paint()
paint.color = Color.RED
paint.strokeWidth = 10F
// Setting the bitmap on ImageView
mImageView.setImageBitmap(bitmap)
// Setting onTouchListener on the ImageView
mImageView.setOnTouchListener(this)
}
// When Touch is detected on the ImageView,
// Initial and final coordinates are recorded
// and a line is drawn between them.
// ImagView is updated
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
when (event!!.action) {
MotionEvent.ACTION_DOWN -> {
downX = event.x
downY = event.y
}
MotionEvent.ACTION_UP -> {
upX = event.x
upY = event.y
canvas.drawLine(downX, downY, upX, upY, paint)
mImageView.invalidate()
}
}
return true
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
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:id="@+id/image_view_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="ContentDescription"
android:background="@color/black"/>
</RelativeLayout>
Practical 4 ( Caculator )
Main.kt

package com.example.calculator

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val etNumber1: EditText = findViewById(R.id.etNumber1)


val etNumber2: EditText = findViewById(R.id.etNumber2)
val btnAdd: Button = findViewById(R.id.btnAdd)
val btnSubtract: Button = findViewById(R.id.btnSubtract)
val btnMultiply: Button = findViewById(R.id.btnMultiply)
val btnDivide: Button = findViewById(R.id.btnDivide)
val tvResult: TextView = findViewById(R.id.tvResult)

btnAdd.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "add")
}

btnSubtract.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "subtract")
}

btnMultiply.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "multiply")
}

btnDivide.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "divide")
}
}

private fun calculate(etNumber1: EditText, etNumber2: EditText, tvResult: TextView, operation:


String) {
val number1 = etNumber1.text.toString()
val number2 = etNumber2.text.toString()
if (number1.isEmpty() || number2.isEmpty()) {
Toast.makeText(this, "Please enter both numbers", Toast.LENGTH_SHORT).show()
return
}

val num1 = number1.toDouble()


val num2 = number2.toDouble()
val result = when (operation) {
"add" -> num1 + num2
"subtract" -> num1 - num2
"multiply" -> num1 * num2
"divide" -> {
if (num2 == 0.0) {
Toast.makeText(this, "Cannot divide by zero", Toast.LENGTH_SHORT).show()
return
} else {
num1 / num2
}
}
else -> 0.0
}
tvResult.text = "Result: $result"
}
}

main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/etNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal"
android:layout_marginBottom="8dp"/>

<EditText
android:id="@+id/etNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal"
android:layout_marginBottom="16dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">

<Button
android:id="@+id/btnAdd"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="+" />

<Button
android:id="@+id/btnSubtract"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="-" />

<Button
android:id="@+id/btnMultiply"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="*" />

<Button
android:id="@+id/btnDivide"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="/" />
</LinearLayout>

<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Result: "
android:textSize="18sp"
android:textStyle="bold" />

</LinearLayout>
Prcatical 5 ( ImageFlliper )
Main.kt

package com.example.imageflipper

import android.os.Bundle
import android.widget.Button
import android.widget.ViewFlipper
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Reference to ViewFlipper
val viewFlipper: ViewFlipper = findViewById(R.id.viewFlipper)

// Reference to buttons
val nextButton: Button = findViewById(R.id.buttonNext)
val prevButton: Button = findViewById(R.id.buttonPrev)

// Next button click listener


nextButton.setOnClickListener {
viewFlipper.showNext()
}

// Previous button click listener


prevButton.setOnClickListener {
viewFlipper.showPrevious()
}
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<!-- ViewFlipper to flip images -->


<ViewFlipper
android:id="@+id/viewFlipper"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_centerInParent="true">

<!-- Add images for flipping -->


<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/shoes"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/cap"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/tshirts"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/pokemon"
android:scaleType="centerCrop" />
</ViewFlipper>

<!-- Buttons to navigate -->


<Button
android:id="@+id/buttonPrev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />

<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />
</RelativeLayout>
Prcatical 6 ( MemoryGame )
Main.kt

package com.example.memorygame

import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var gridView: GridView


private lateinit var imageAdapter: ImageAdapter
private lateinit var resultImage: ImageView
private lateinit var actionButton: Button
private val handler = Handler()

// Images and game logic


private val images = arrayOf(
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon,
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon
)
private var shuffledImages = images.toList().shuffled()
private var firstCardIndex = -1
private var secondCardIndex = -1
private var score = 0
private var wrongFlips = 0
private val maxWrongFlips = 4
private var flippedCards = mutableSetOf<Int>()

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

gridView = findViewById(R.id.gridView)
resultImage = findViewById(R.id.resultImage)
actionButton = findViewById(R.id.actionButton)

startGame()

actionButton.setOnClickListener {
resetGame()
}

gridView.setOnItemClickListener { _, _, position, _ ->


if (flippedCards.contains(position) || firstCardIndex == position || wrongFlips >=
maxWrongFlips) {
return@setOnItemClickListener
}

// Flip the card


imageAdapter.revealCard(position)
imageAdapter.notifyDataSetChanged()

if (firstCardIndex == -1) {
// First card selected
firstCardIndex = position
} else if (secondCardIndex == -1) {
// Second card selected
secondCardIndex = position

// Check for match


checkForMatch()
}
}
}

private fun startGame() {


shuffledImages = images.toList().shuffled()
imageAdapter = ImageAdapter(this, shuffledImages)
gridView.adapter = imageAdapter

// Reset variables
firstCardIndex = -1
secondCardIndex = -1
score = 0
wrongFlips = 0
flippedCards.clear()

// Hide result image and button


resultImage.visibility = View.GONE
actionButton.visibility = View.GONE
gridView.visibility = View.VISIBLE
}

private fun checkForMatch() {


handler.postDelayed({
if (shuffledImages[firstCardIndex] == shuffledImages[secondCardIndex]) {
// Cards match
flippedCards.add(firstCardIndex)
flippedCards.add(secondCardIndex)
score += 1

// Check for game completion


if (flippedCards.size == shuffledImages.size) {
showWin()
}
} else {
// Cards don't match, hide them and increment wrong flip count
imageAdapter.hideCard(firstCardIndex)
imageAdapter.hideCard(secondCardIndex)
wrongFlips += 1

if (wrongFlips >= maxWrongFlips) {


showFailure()
}
}

// Reset selection
firstCardIndex = -1
secondCardIndex = -1
imageAdapter.notifyDataSetChanged()
}, 1000)
}

private fun showWin() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.happy)
resultImage.visibility = View.VISIBLE
actionButton.text = "Reset"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Win!", Toast.LENGTH_SHORT).show()
}

private fun showFailure() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.failed)
resultImage.visibility = View.VISIBLE
actionButton.text = "Retry"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Failed! Retry the game.", Toast.LENGTH_SHORT).show()
}

private fun resetGame() {


startGame()
Toast.makeText(this, "Game Reset! Good luck!", Toast.LENGTH_SHORT).show()
}
}

ImageAdapter.kt
package com.example.memorygame

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView

class ImageAdapter(private val context: Context, private val images: List<Int>) : BaseAdapter() {

private val revealedCards = BooleanArray(images.size)

override fun getCount(): Int = images.size

override fun getItem(position: Int): Any = images[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val imageView: ImageView = convertView as? ImageView ?: ImageView(context)

imageView.layoutParams = ViewGroup.LayoutParams(200, 200)


imageView.scaleType = ImageView.ScaleType.CENTER_CROP
imageView.setPadding(8, 8, 8, 8)

if (revealedCards[position]) {
imageView.setImageResource(images[position]) // Show the image
} else {
imageView.setImageResource(R.drawable.card_back) // Show the card back
}

return imageView
}

fun revealCard(position: Int) {


revealedCards[position] = true
}

fun hideCard(position: Int) {


revealedCards[position] = false
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<ImageView
android:id="@+id/resultImage"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:visibility="gone" />

<Button
android:id="@+id/actionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:visibility="gone"
android:layout_below="@id/resultImage"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="4"
android:horizontalSpacing="8dp"
android:verticalSpacing="8dp"
android:gravity="center"
android:layout_above="@id/resultImage"
android:padding="8dp" />
</RelativeLayout>
Practical 7 ( Quiz Game )
Main.kt

package com.example.quizapp

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private val questions = listOf(


Question("What is the capital of France?", listOf("Paris", "Berlin", "Madrid", "Rome"), 0),
Question("What is 5 + 3?", listOf("5", "8", "10", "15"), 1),
Question("Who wrote 'Romeo and Juliet'?", listOf("Shakespeare", "Hemingway", "Austen",
"Tolkien"), 0)
)

private var currentQuestionIndex = 0


private var score = 0

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val tvQuestion: TextView = findViewById(R.id.tvQuestion)


val rgOptions: RadioGroup = findViewById(R.id.rgOptions)
val btnSubmit: Button = findViewById(R.id.btnSubmit)
val tvFeedback: TextView = findViewById(R.id.tvFeedback)
val btnRetry: Button = findViewById(R.id.btnRetry)
val btnNext: Button = findViewById(R.id.btnNext)

fun loadQuestion() {
val question = questions[currentQuestionIndex]
tvQuestion.text = question.text

rgOptions.removeAllViews()
for ((index, option) in question.options.withIndex()) {
val radioButton = RadioButton(this)
radioButton.text = option
radioButton.id = index
rgOptions.addView(radioButton)
}

tvFeedback.text = ""
}

fun showResults() {
if (score >= 2) {
tvFeedback.text = "You passed! Score: $score/${questions.size}"
tvFeedback.setTextColor(getColor(android.R.color.holo_green_dark))
btnNext.visibility = Button.VISIBLE
btnRetry.visibility = Button.GONE
} else {
tvFeedback.text = "You failed. Score: $score/${questions.size}. Try again!"
tvFeedback.setTextColor(getColor(android.R.color.holo_red_dark))
btnRetry.visibility = Button.VISIBLE
btnNext.visibility = Button.GONE
}
btnSubmit.visibility = Button.GONE
}

btnSubmit.setOnClickListener {
val selectedOptionId = rgOptions.checkedRadioButtonId

if (selectedOptionId == -1) {
Toast.makeText(this, "Please select an option!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}

val question = questions[currentQuestionIndex]


if (selectedOptionId == question.correctOption) {
score++
}

currentQuestionIndex++
if (currentQuestionIndex < questions.size) {
loadQuestion()
} else {
showResults()
}
}

btnRetry.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Welcome back! Let's start again!"
loadQuestion()
}

btnNext.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Here’s your next quiz!"
loadQuestion()
}

loadQuestion()
}

data class Question(


val text: String,
val options: List<String>,
val correctOption: Int
)
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/tvQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to the Quiz!"
android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="16dp" />

<RadioGroup
android:id="@+id/rgOptions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />

<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp" />

<TextView
android:id="@+id/tvFeedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="16sp"
android:gravity="center"
android:layout_marginTop="16dp" />

<Button
android:id="@+id/btnRetry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retry"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />

<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Quiz"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />
</LinearLayout>

Practical 8 ( HeadTail )
Main.kt

package com.example.headtailgame

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import kotlin.random.Random

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Get references to UI elements


val coinImageView: ImageView = findViewById(R.id.coinImageView)
val resultTextView: TextView = findViewById(R.id.resultTextView)
val flipButton: Button = findViewById(R.id.flipButton)

// Handle button click


flipButton.setOnClickListener {
// Temporarily disable the button during the "flip"
flipButton.isEnabled = false
resultTextView.text = "Flipping..."

// Simulate a delay for randomness (e.g., 1 second)


Handler().postDelayed({
// Randomly choose between 0 (Head) and 1 (Tail)
val randomFlip = Random.nextInt(2)

// Update the ImageView and TextView based on the result


if (randomFlip == 0) {
coinImageView.setImageResource(R.drawable.f) // Head
resultTextView.text = "It's Head!"
} else {
coinImageView.setImageResource(R.drawable.b) // Tail
resultTextView.text = "It's Tail!"
}

// Re-enable the button after flipping


flipButton.isEnabled = true
}, 1000) // Delay for 1 second
}
}
}

Main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">

<!-- ImageView to display the coin -->


<ImageView
android:id="@+id/coinImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/f" />

<!-- TextView to display the flip result -->


<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip the coin!"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="16dp" />

<!-- Button to flip the coin -->


<Button
android:id="@+id/flipButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip Coin"
android:layout_marginTop="24dp" />

</LinearLayout>
Practical 1 ( Gridviewexample )
Main.kt

package com.example.gridviewexample

import android.os.Bundle
import android.widget.GridView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val gridView: GridView = findViewById(R.id.gridView)

// Create the list of items with titles and image resource IDs
var courseList = listOf<GridViewModal>()
courseList = courseList + GridViewModal("Tshirts", R.drawable.tshirts)
courseList = courseList + GridViewModal("Cap", R.drawable.cap)
courseList = courseList + GridViewModal("Shoes", R.drawable.shoes)
courseList = courseList + GridViewModal("Python", R.drawable.python)
courseList = courseList + GridViewModal("Javascript", R.drawable.js)

// Set up the adapter with the course list


val adapter = GridViewAdapter(this, courseList)
gridView.adapter = adapter
}
}

Adapter.kt

package com.example.gridviewexample

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView

data class GridViewModal(val title: String, val imageResId: Int)

class GridViewAdapter(private val context: Context, private val items: List<GridViewModal>) :


BaseAdapter() {
override fun getCount(): Int = items.size

override fun getItem(position: Int): Any = items[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val view: View = convertView ?: LayoutInflater.from(context).inflate(R.layout.grid_item, parent,
false)

// Bind image and title to the layout


val imageView: ImageView = view.findViewById(R.id.imageView)
val textView: TextView = view.findViewById(R.id.textView)

val item = items[position]


imageView.setImageResource(item.imageResId)
textView.text = item.title

return view
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" />
</RelativeLayout>

Grid.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="5dp">

<ImageView
android:id="@+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="centerCrop" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textColor="#000"
android:textSize="14sp"
android:gravity="center" />
</LinearLayout>

Practical 2 ( Radio Buttons )


Main.kt

package com.example.androidpractical2

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


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

// Input and Show Button


val editText = findViewById<EditText>(R.id.editText)
val buttonShowInput = findViewById<Button>(R.id.buttonShowInput)
buttonShowInput.setOnClickListener {
val inputText = editText.text.toString()
Toast.makeText(this, inputText, Toast.LENGTH_SHORT).show()
}

// RadioGroup and Get Color Button


val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
val buttonGetColor = findViewById<Button>(R.id.buttonGetColor)
buttonGetColor.setOnClickListener {
val selectedRadioId = radioGroup.checkedRadioButtonId
if (selectedRadioId != -1) {
val selectedRadioButton = findViewById<RadioButton>(selectedRadioId)
Toast.makeText(this, "Selected: ${selectedRadioButton.text}", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Please select a color", Toast.LENGTH_SHORT).show()
}
}

// Checkbox Button
val checkBoxCS = findViewById<CheckBox>(R.id.checkBoxCS)
val checkBoxIT = findViewById<CheckBox>(R.id.checkBoxIT)
val buttonSubmit = findViewById<Button>(R.id.buttonSubmit)
buttonSubmit.setOnClickListener {
val selectedOptions = mutableListOf<String>()
if (checkBoxCS.isChecked) selectedOptions.add("CS")
if (checkBoxIT.isChecked) selectedOptions.add("IT")
Toast.makeText(this, "Selected: ${selectedOptions.joinToString(", ")}",
Toast.LENGTH_SHORT).show()
}

// Spinner
val spinnerLanguage = findViewById<Spinner>(R.id.spinnerLanguage)
val languages = arrayOf("Java", "Kotlin", "C++", "Python")
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerLanguage.adapter = adapter

spinnerLanguage.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {


override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Toast.makeText(this@MainActivity, "Selected: ${languages[position]}",
Toast.LENGTH_SHORT).show()
}

override fun onNothingSelected(parent: AdapterView<*>?) {


// Do nothing
}
}
}
}

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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Input"
android:layout_margin="16dp"
android:inputType="text"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonShowInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Show Input"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/editText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonShowInput">

<TextView
android:id="@+id/radioGroupTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Which is your favorite color?"
android:textStyle="bold"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioYellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yellow"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioPink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pink"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioGreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green"
android:textColor="@android:color/white" />
</RadioGroup>

<Button
android:id="@+id/buttonGetColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Color"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toStartOf="@id/radioGroup"
app:layout_constraintTop_toBottomOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewDemo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView Demo"
android:textColor="@android:color/white"
app:layout_constraintTop_toTopOf="@id/radioGroup"
app:layout_constraintStart_toEndOf="@id/radioGroup"
app:layout_constraintEnd_toEndOf="parent" />

<CheckBox
android:id="@+id/checkBoxCS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CS"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/textViewDemo"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<CheckBox
android:id="@+id/checkBoxIT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IT"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/checkBoxCS"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/checkBoxIT"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Language"
android:textColor="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />

<Spinner
android:id="@+id/spinnerLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toEndOf="@id/textViewLanguage"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />
</androidx.constraintlayout.widget.ConstraintLayout>

Practical 3 ( Canva )
Main.kt

package com.example.canvas
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
class MainActivity : AppCompatActivity(), View.OnTouchListener {
// Declaring ImageView, Bitmap, Canvas, Paint,
// Down Coordinates and Up Coordinates
private lateinit var mImageView: ImageView
private lateinit var bitmap: Bitmap
private lateinit var canvas: Canvas
private lateinit var paint: Paint
private var downX = 0f
private var downY = 0f
private var upX = 0f
private var upY = 0f
@RequiresApi(Build.VERSION_CODES.R)
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initializing the ImageView
mImageView = findViewById(R.id.image_view_1)
// Getting the current window dimensions
val currentDisplay = windowManager.currentWindowMetrics
val dw = currentDisplay.bounds.width()
val dh = currentDisplay.bounds.height()
// Creating a bitmap with fetched dimensions
bitmap = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888)
// Storing the canvas on the bitmap
canvas = Canvas(bitmap)
// Initializing Paint to determine
// stoke attributes like color and size
paint = Paint()
paint.color = Color.RED
paint.strokeWidth = 10F
// Setting the bitmap on ImageView
mImageView.setImageBitmap(bitmap)
// Setting onTouchListener on the ImageView
mImageView.setOnTouchListener(this)
}
// When Touch is detected on the ImageView,
// Initial and final coordinates are recorded
// and a line is drawn between them.
// ImagView is updated
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
when (event!!.action) {
MotionEvent.ACTION_DOWN -> {
downX = event.x
downY = event.y
}
MotionEvent.ACTION_UP -> {
upX = event.x
upY = event.y
canvas.drawLine(downX, downY, upX, upY, paint)
mImageView.invalidate()
}
}
return true
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
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:id="@+id/image_view_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="ContentDescription"
android:background="@color/black"/>
</RelativeLayout>
Practical 4 ( Caculator )
Main.kt

package com.example.calculator

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val etNumber1: EditText = findViewById(R.id.etNumber1)


val etNumber2: EditText = findViewById(R.id.etNumber2)
val btnAdd: Button = findViewById(R.id.btnAdd)
val btnSubtract: Button = findViewById(R.id.btnSubtract)
val btnMultiply: Button = findViewById(R.id.btnMultiply)
val btnDivide: Button = findViewById(R.id.btnDivide)
val tvResult: TextView = findViewById(R.id.tvResult)

btnAdd.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "add")
}

btnSubtract.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "subtract")
}

btnMultiply.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "multiply")
}

btnDivide.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "divide")
}
}

private fun calculate(etNumber1: EditText, etNumber2: EditText, tvResult: TextView, operation:


String) {
val number1 = etNumber1.text.toString()
val number2 = etNumber2.text.toString()
if (number1.isEmpty() || number2.isEmpty()) {
Toast.makeText(this, "Please enter both numbers", Toast.LENGTH_SHORT).show()
return
}

val num1 = number1.toDouble()


val num2 = number2.toDouble()
val result = when (operation) {
"add" -> num1 + num2
"subtract" -> num1 - num2
"multiply" -> num1 * num2
"divide" -> {
if (num2 == 0.0) {
Toast.makeText(this, "Cannot divide by zero", Toast.LENGTH_SHORT).show()
return
} else {
num1 / num2
}
}
else -> 0.0
}
tvResult.text = "Result: $result"
}
}

main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/etNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal"
android:layout_marginBottom="8dp"/>

<EditText
android:id="@+id/etNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal"
android:layout_marginBottom="16dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">

<Button
android:id="@+id/btnAdd"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="+" />

<Button
android:id="@+id/btnSubtract"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="-" />

<Button
android:id="@+id/btnMultiply"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="*" />

<Button
android:id="@+id/btnDivide"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="/" />
</LinearLayout>

<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Result: "
android:textSize="18sp"
android:textStyle="bold" />

</LinearLayout>
Prcatical 5 ( ImageFlliper )
Main.kt

package com.example.imageflipper

import android.os.Bundle
import android.widget.Button
import android.widget.ViewFlipper
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Reference to ViewFlipper
val viewFlipper: ViewFlipper = findViewById(R.id.viewFlipper)

// Reference to buttons
val nextButton: Button = findViewById(R.id.buttonNext)
val prevButton: Button = findViewById(R.id.buttonPrev)

// Next button click listener


nextButton.setOnClickListener {
viewFlipper.showNext()
}

// Previous button click listener


prevButton.setOnClickListener {
viewFlipper.showPrevious()
}
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<!-- ViewFlipper to flip images -->


<ViewFlipper
android:id="@+id/viewFlipper"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_centerInParent="true">

<!-- Add images for flipping -->


<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/shoes"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/cap"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/tshirts"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/pokemon"
android:scaleType="centerCrop" />
</ViewFlipper>

<!-- Buttons to navigate -->


<Button
android:id="@+id/buttonPrev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />

<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />
</RelativeLayout>
Prcatical 6 ( MemoryGame )
Main.kt

package com.example.memorygame

import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var gridView: GridView


private lateinit var imageAdapter: ImageAdapter
private lateinit var resultImage: ImageView
private lateinit var actionButton: Button
private val handler = Handler()

// Images and game logic


private val images = arrayOf(
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon,
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon
)
private var shuffledImages = images.toList().shuffled()
private var firstCardIndex = -1
private var secondCardIndex = -1
private var score = 0
private var wrongFlips = 0
private val maxWrongFlips = 4
private var flippedCards = mutableSetOf<Int>()

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

gridView = findViewById(R.id.gridView)
resultImage = findViewById(R.id.resultImage)
actionButton = findViewById(R.id.actionButton)

startGame()

actionButton.setOnClickListener {
resetGame()
}

gridView.setOnItemClickListener { _, _, position, _ ->


if (flippedCards.contains(position) || firstCardIndex == position || wrongFlips >=
maxWrongFlips) {
return@setOnItemClickListener
}

// Flip the card


imageAdapter.revealCard(position)
imageAdapter.notifyDataSetChanged()

if (firstCardIndex == -1) {
// First card selected
firstCardIndex = position
} else if (secondCardIndex == -1) {
// Second card selected
secondCardIndex = position

// Check for match


checkForMatch()
}
}
}

private fun startGame() {


shuffledImages = images.toList().shuffled()
imageAdapter = ImageAdapter(this, shuffledImages)
gridView.adapter = imageAdapter

// Reset variables
firstCardIndex = -1
secondCardIndex = -1
score = 0
wrongFlips = 0
flippedCards.clear()

// Hide result image and button


resultImage.visibility = View.GONE
actionButton.visibility = View.GONE
gridView.visibility = View.VISIBLE
}

private fun checkForMatch() {


handler.postDelayed({
if (shuffledImages[firstCardIndex] == shuffledImages[secondCardIndex]) {
// Cards match
flippedCards.add(firstCardIndex)
flippedCards.add(secondCardIndex)
score += 1

// Check for game completion


if (flippedCards.size == shuffledImages.size) {
showWin()
}
} else {
// Cards don't match, hide them and increment wrong flip count
imageAdapter.hideCard(firstCardIndex)
imageAdapter.hideCard(secondCardIndex)
wrongFlips += 1

if (wrongFlips >= maxWrongFlips) {


showFailure()
}
}

// Reset selection
firstCardIndex = -1
secondCardIndex = -1
imageAdapter.notifyDataSetChanged()
}, 1000)
}

private fun showWin() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.happy)
resultImage.visibility = View.VISIBLE
actionButton.text = "Reset"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Win!", Toast.LENGTH_SHORT).show()
}

private fun showFailure() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.failed)
resultImage.visibility = View.VISIBLE
actionButton.text = "Retry"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Failed! Retry the game.", Toast.LENGTH_SHORT).show()
}

private fun resetGame() {


startGame()
Toast.makeText(this, "Game Reset! Good luck!", Toast.LENGTH_SHORT).show()
}
}

ImageAdapter.kt
package com.example.memorygame

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView

class ImageAdapter(private val context: Context, private val images: List<Int>) : BaseAdapter() {

private val revealedCards = BooleanArray(images.size)

override fun getCount(): Int = images.size

override fun getItem(position: Int): Any = images[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val imageView: ImageView = convertView as? ImageView ?: ImageView(context)

imageView.layoutParams = ViewGroup.LayoutParams(200, 200)


imageView.scaleType = ImageView.ScaleType.CENTER_CROP
imageView.setPadding(8, 8, 8, 8)

if (revealedCards[position]) {
imageView.setImageResource(images[position]) // Show the image
} else {
imageView.setImageResource(R.drawable.card_back) // Show the card back
}

return imageView
}

fun revealCard(position: Int) {


revealedCards[position] = true
}

fun hideCard(position: Int) {


revealedCards[position] = false
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<ImageView
android:id="@+id/resultImage"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:visibility="gone" />

<Button
android:id="@+id/actionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:visibility="gone"
android:layout_below="@id/resultImage"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="4"
android:horizontalSpacing="8dp"
android:verticalSpacing="8dp"
android:gravity="center"
android:layout_above="@id/resultImage"
android:padding="8dp" />
</RelativeLayout>
Practical 7 ( Quiz Game )
Main.kt

package com.example.quizapp

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private val questions = listOf(


Question("What is the capital of France?", listOf("Paris", "Berlin", "Madrid", "Rome"), 0),
Question("What is 5 + 3?", listOf("5", "8", "10", "15"), 1),
Question("Who wrote 'Romeo and Juliet'?", listOf("Shakespeare", "Hemingway", "Austen",
"Tolkien"), 0)
)

private var currentQuestionIndex = 0


private var score = 0

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val tvQuestion: TextView = findViewById(R.id.tvQuestion)


val rgOptions: RadioGroup = findViewById(R.id.rgOptions)
val btnSubmit: Button = findViewById(R.id.btnSubmit)
val tvFeedback: TextView = findViewById(R.id.tvFeedback)
val btnRetry: Button = findViewById(R.id.btnRetry)
val btnNext: Button = findViewById(R.id.btnNext)

fun loadQuestion() {
val question = questions[currentQuestionIndex]
tvQuestion.text = question.text

rgOptions.removeAllViews()
for ((index, option) in question.options.withIndex()) {
val radioButton = RadioButton(this)
radioButton.text = option
radioButton.id = index
rgOptions.addView(radioButton)
}

tvFeedback.text = ""
}

fun showResults() {
if (score >= 2) {
tvFeedback.text = "You passed! Score: $score/${questions.size}"
tvFeedback.setTextColor(getColor(android.R.color.holo_green_dark))
btnNext.visibility = Button.VISIBLE
btnRetry.visibility = Button.GONE
} else {
tvFeedback.text = "You failed. Score: $score/${questions.size}. Try again!"
tvFeedback.setTextColor(getColor(android.R.color.holo_red_dark))
btnRetry.visibility = Button.VISIBLE
btnNext.visibility = Button.GONE
}
btnSubmit.visibility = Button.GONE
}

btnSubmit.setOnClickListener {
val selectedOptionId = rgOptions.checkedRadioButtonId

if (selectedOptionId == -1) {
Toast.makeText(this, "Please select an option!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}

val question = questions[currentQuestionIndex]


if (selectedOptionId == question.correctOption) {
score++
}

currentQuestionIndex++
if (currentQuestionIndex < questions.size) {
loadQuestion()
} else {
showResults()
}
}

btnRetry.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Welcome back! Let's start again!"
loadQuestion()
}

btnNext.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Here’s your next quiz!"
loadQuestion()
}

loadQuestion()
}

data class Question(


val text: String,
val options: List<String>,
val correctOption: Int
)
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/tvQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to the Quiz!"
android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="16dp" />

<RadioGroup
android:id="@+id/rgOptions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />

<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp" />

<TextView
android:id="@+id/tvFeedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="16sp"
android:gravity="center"
android:layout_marginTop="16dp" />

<Button
android:id="@+id/btnRetry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retry"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />

<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Quiz"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />
</LinearLayout>

Practical 8 ( HeadTail )
Main.kt

package com.example.headtailgame

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import kotlin.random.Random

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Get references to UI elements


val coinImageView: ImageView = findViewById(R.id.coinImageView)
val resultTextView: TextView = findViewById(R.id.resultTextView)
val flipButton: Button = findViewById(R.id.flipButton)

// Handle button click


flipButton.setOnClickListener {
// Temporarily disable the button during the "flip"
flipButton.isEnabled = false
resultTextView.text = "Flipping..."

// Simulate a delay for randomness (e.g., 1 second)


Handler().postDelayed({
// Randomly choose between 0 (Head) and 1 (Tail)
val randomFlip = Random.nextInt(2)

// Update the ImageView and TextView based on the result


if (randomFlip == 0) {
coinImageView.setImageResource(R.drawable.f) // Head
resultTextView.text = "It's Head!"
} else {
coinImageView.setImageResource(R.drawable.b) // Tail
resultTextView.text = "It's Tail!"
}

// Re-enable the button after flipping


flipButton.isEnabled = true
}, 1000) // Delay for 1 second
}
}
}

Main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">

<!-- ImageView to display the coin -->


<ImageView
android:id="@+id/coinImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/f" />

<!-- TextView to display the flip result -->


<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip the coin!"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="16dp" />

<!-- Button to flip the coin -->


<Button
android:id="@+id/flipButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip Coin"
android:layout_marginTop="24dp" />

</LinearLayout>
Practical 1 ( Gridviewexample )
Main.kt

package com.example.gridviewexample

import android.os.Bundle
import android.widget.GridView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val gridView: GridView = findViewById(R.id.gridView)

// Create the list of items with titles and image resource IDs
var courseList = listOf<GridViewModal>()
courseList = courseList + GridViewModal("Tshirts", R.drawable.tshirts)
courseList = courseList + GridViewModal("Cap", R.drawable.cap)
courseList = courseList + GridViewModal("Shoes", R.drawable.shoes)
courseList = courseList + GridViewModal("Python", R.drawable.python)
courseList = courseList + GridViewModal("Javascript", R.drawable.js)

// Set up the adapter with the course list


val adapter = GridViewAdapter(this, courseList)
gridView.adapter = adapter
}
}

Adapter.kt

package com.example.gridviewexample

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView

data class GridViewModal(val title: String, val imageResId: Int)

class GridViewAdapter(private val context: Context, private val items: List<GridViewModal>) :


BaseAdapter() {
override fun getCount(): Int = items.size

override fun getItem(position: Int): Any = items[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val view: View = convertView ?: LayoutInflater.from(context).inflate(R.layout.grid_item, parent,
false)

// Bind image and title to the layout


val imageView: ImageView = view.findViewById(R.id.imageView)
val textView: TextView = view.findViewById(R.id.textView)

val item = items[position]


imageView.setImageResource(item.imageResId)
textView.text = item.title

return view
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" />
</RelativeLayout>

Grid.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="5dp">

<ImageView
android:id="@+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="centerCrop" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textColor="#000"
android:textSize="14sp"
android:gravity="center" />
</LinearLayout>

Practical 2 ( Radio Buttons )


Main.kt

package com.example.androidpractical2

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


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

// Input and Show Button


val editText = findViewById<EditText>(R.id.editText)
val buttonShowInput = findViewById<Button>(R.id.buttonShowInput)
buttonShowInput.setOnClickListener {
val inputText = editText.text.toString()
Toast.makeText(this, inputText, Toast.LENGTH_SHORT).show()
}

// RadioGroup and Get Color Button


val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
val buttonGetColor = findViewById<Button>(R.id.buttonGetColor)
buttonGetColor.setOnClickListener {
val selectedRadioId = radioGroup.checkedRadioButtonId
if (selectedRadioId != -1) {
val selectedRadioButton = findViewById<RadioButton>(selectedRadioId)
Toast.makeText(this, "Selected: ${selectedRadioButton.text}", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Please select a color", Toast.LENGTH_SHORT).show()
}
}

// Checkbox Button
val checkBoxCS = findViewById<CheckBox>(R.id.checkBoxCS)
val checkBoxIT = findViewById<CheckBox>(R.id.checkBoxIT)
val buttonSubmit = findViewById<Button>(R.id.buttonSubmit)
buttonSubmit.setOnClickListener {
val selectedOptions = mutableListOf<String>()
if (checkBoxCS.isChecked) selectedOptions.add("CS")
if (checkBoxIT.isChecked) selectedOptions.add("IT")
Toast.makeText(this, "Selected: ${selectedOptions.joinToString(", ")}",
Toast.LENGTH_SHORT).show()
}

// Spinner
val spinnerLanguage = findViewById<Spinner>(R.id.spinnerLanguage)
val languages = arrayOf("Java", "Kotlin", "C++", "Python")
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerLanguage.adapter = adapter

spinnerLanguage.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {


override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Toast.makeText(this@MainActivity, "Selected: ${languages[position]}",
Toast.LENGTH_SHORT).show()
}

override fun onNothingSelected(parent: AdapterView<*>?) {


// Do nothing
}
}
}
}

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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Input"
android:layout_margin="16dp"
android:inputType="text"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonShowInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Show Input"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/editText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonShowInput">

<TextView
android:id="@+id/radioGroupTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Which is your favorite color?"
android:textStyle="bold"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioYellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yellow"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioPink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pink"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioGreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green"
android:textColor="@android:color/white" />
</RadioGroup>

<Button
android:id="@+id/buttonGetColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Color"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toStartOf="@id/radioGroup"
app:layout_constraintTop_toBottomOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewDemo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView Demo"
android:textColor="@android:color/white"
app:layout_constraintTop_toTopOf="@id/radioGroup"
app:layout_constraintStart_toEndOf="@id/radioGroup"
app:layout_constraintEnd_toEndOf="parent" />

<CheckBox
android:id="@+id/checkBoxCS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CS"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/textViewDemo"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<CheckBox
android:id="@+id/checkBoxIT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IT"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/checkBoxCS"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/checkBoxIT"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Language"
android:textColor="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />

<Spinner
android:id="@+id/spinnerLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toEndOf="@id/textViewLanguage"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />
</androidx.constraintlayout.widget.ConstraintLayout>

Practical 3 ( Canva )
Main.kt

package com.example.canvas
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
class MainActivity : AppCompatActivity(), View.OnTouchListener {
// Declaring ImageView, Bitmap, Canvas, Paint,
// Down Coordinates and Up Coordinates
private lateinit var mImageView: ImageView
private lateinit var bitmap: Bitmap
private lateinit var canvas: Canvas
private lateinit var paint: Paint
private var downX = 0f
private var downY = 0f
private var upX = 0f
private var upY = 0f
@RequiresApi(Build.VERSION_CODES.R)
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initializing the ImageView
mImageView = findViewById(R.id.image_view_1)
// Getting the current window dimensions
val currentDisplay = windowManager.currentWindowMetrics
val dw = currentDisplay.bounds.width()
val dh = currentDisplay.bounds.height()
// Creating a bitmap with fetched dimensions
bitmap = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888)
// Storing the canvas on the bitmap
canvas = Canvas(bitmap)
// Initializing Paint to determine
// stoke attributes like color and size
paint = Paint()
paint.color = Color.RED
paint.strokeWidth = 10F
// Setting the bitmap on ImageView
mImageView.setImageBitmap(bitmap)
// Setting onTouchListener on the ImageView
mImageView.setOnTouchListener(this)
}
// When Touch is detected on the ImageView,
// Initial and final coordinates are recorded
// and a line is drawn between them.
// ImagView is updated
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
when (event!!.action) {
MotionEvent.ACTION_DOWN -> {
downX = event.x
downY = event.y
}
MotionEvent.ACTION_UP -> {
upX = event.x
upY = event.y
canvas.drawLine(downX, downY, upX, upY, paint)
mImageView.invalidate()
}
}
return true
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
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:id="@+id/image_view_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="ContentDescription"
android:background="@color/black"/>
</RelativeLayout>
Practical 4 ( Caculator )
Main.kt

package com.example.calculator

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val etNumber1: EditText = findViewById(R.id.etNumber1)


val etNumber2: EditText = findViewById(R.id.etNumber2)
val btnAdd: Button = findViewById(R.id.btnAdd)
val btnSubtract: Button = findViewById(R.id.btnSubtract)
val btnMultiply: Button = findViewById(R.id.btnMultiply)
val btnDivide: Button = findViewById(R.id.btnDivide)
val tvResult: TextView = findViewById(R.id.tvResult)

btnAdd.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "add")
}

btnSubtract.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "subtract")
}

btnMultiply.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "multiply")
}

btnDivide.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "divide")
}
}

private fun calculate(etNumber1: EditText, etNumber2: EditText, tvResult: TextView, operation:


String) {
val number1 = etNumber1.text.toString()
val number2 = etNumber2.text.toString()
if (number1.isEmpty() || number2.isEmpty()) {
Toast.makeText(this, "Please enter both numbers", Toast.LENGTH_SHORT).show()
return
}

val num1 = number1.toDouble()


val num2 = number2.toDouble()
val result = when (operation) {
"add" -> num1 + num2
"subtract" -> num1 - num2
"multiply" -> num1 * num2
"divide" -> {
if (num2 == 0.0) {
Toast.makeText(this, "Cannot divide by zero", Toast.LENGTH_SHORT).show()
return
} else {
num1 / num2
}
}
else -> 0.0
}
tvResult.text = "Result: $result"
}
}

main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/etNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal"
android:layout_marginBottom="8dp"/>

<EditText
android:id="@+id/etNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal"
android:layout_marginBottom="16dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">

<Button
android:id="@+id/btnAdd"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="+" />

<Button
android:id="@+id/btnSubtract"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="-" />

<Button
android:id="@+id/btnMultiply"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="*" />

<Button
android:id="@+id/btnDivide"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="/" />
</LinearLayout>

<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Result: "
android:textSize="18sp"
android:textStyle="bold" />

</LinearLayout>
Prcatical 5 ( ImageFlliper )
Main.kt

package com.example.imageflipper

import android.os.Bundle
import android.widget.Button
import android.widget.ViewFlipper
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Reference to ViewFlipper
val viewFlipper: ViewFlipper = findViewById(R.id.viewFlipper)

// Reference to buttons
val nextButton: Button = findViewById(R.id.buttonNext)
val prevButton: Button = findViewById(R.id.buttonPrev)

// Next button click listener


nextButton.setOnClickListener {
viewFlipper.showNext()
}

// Previous button click listener


prevButton.setOnClickListener {
viewFlipper.showPrevious()
}
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<!-- ViewFlipper to flip images -->


<ViewFlipper
android:id="@+id/viewFlipper"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_centerInParent="true">

<!-- Add images for flipping -->


<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/shoes"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/cap"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/tshirts"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/pokemon"
android:scaleType="centerCrop" />
</ViewFlipper>

<!-- Buttons to navigate -->


<Button
android:id="@+id/buttonPrev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />

<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />
</RelativeLayout>
Prcatical 6 ( MemoryGame )
Main.kt

package com.example.memorygame

import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var gridView: GridView


private lateinit var imageAdapter: ImageAdapter
private lateinit var resultImage: ImageView
private lateinit var actionButton: Button
private val handler = Handler()

// Images and game logic


private val images = arrayOf(
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon,
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon
)
private var shuffledImages = images.toList().shuffled()
private var firstCardIndex = -1
private var secondCardIndex = -1
private var score = 0
private var wrongFlips = 0
private val maxWrongFlips = 4
private var flippedCards = mutableSetOf<Int>()

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

gridView = findViewById(R.id.gridView)
resultImage = findViewById(R.id.resultImage)
actionButton = findViewById(R.id.actionButton)

startGame()

actionButton.setOnClickListener {
resetGame()
}

gridView.setOnItemClickListener { _, _, position, _ ->


if (flippedCards.contains(position) || firstCardIndex == position || wrongFlips >=
maxWrongFlips) {
return@setOnItemClickListener
}

// Flip the card


imageAdapter.revealCard(position)
imageAdapter.notifyDataSetChanged()

if (firstCardIndex == -1) {
// First card selected
firstCardIndex = position
} else if (secondCardIndex == -1) {
// Second card selected
secondCardIndex = position

// Check for match


checkForMatch()
}
}
}

private fun startGame() {


shuffledImages = images.toList().shuffled()
imageAdapter = ImageAdapter(this, shuffledImages)
gridView.adapter = imageAdapter

// Reset variables
firstCardIndex = -1
secondCardIndex = -1
score = 0
wrongFlips = 0
flippedCards.clear()

// Hide result image and button


resultImage.visibility = View.GONE
actionButton.visibility = View.GONE
gridView.visibility = View.VISIBLE
}

private fun checkForMatch() {


handler.postDelayed({
if (shuffledImages[firstCardIndex] == shuffledImages[secondCardIndex]) {
// Cards match
flippedCards.add(firstCardIndex)
flippedCards.add(secondCardIndex)
score += 1

// Check for game completion


if (flippedCards.size == shuffledImages.size) {
showWin()
}
} else {
// Cards don't match, hide them and increment wrong flip count
imageAdapter.hideCard(firstCardIndex)
imageAdapter.hideCard(secondCardIndex)
wrongFlips += 1

if (wrongFlips >= maxWrongFlips) {


showFailure()
}
}

// Reset selection
firstCardIndex = -1
secondCardIndex = -1
imageAdapter.notifyDataSetChanged()
}, 1000)
}

private fun showWin() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.happy)
resultImage.visibility = View.VISIBLE
actionButton.text = "Reset"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Win!", Toast.LENGTH_SHORT).show()
}

private fun showFailure() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.failed)
resultImage.visibility = View.VISIBLE
actionButton.text = "Retry"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Failed! Retry the game.", Toast.LENGTH_SHORT).show()
}

private fun resetGame() {


startGame()
Toast.makeText(this, "Game Reset! Good luck!", Toast.LENGTH_SHORT).show()
}
}

ImageAdapter.kt
package com.example.memorygame

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView

class ImageAdapter(private val context: Context, private val images: List<Int>) : BaseAdapter() {

private val revealedCards = BooleanArray(images.size)

override fun getCount(): Int = images.size

override fun getItem(position: Int): Any = images[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val imageView: ImageView = convertView as? ImageView ?: ImageView(context)

imageView.layoutParams = ViewGroup.LayoutParams(200, 200)


imageView.scaleType = ImageView.ScaleType.CENTER_CROP
imageView.setPadding(8, 8, 8, 8)

if (revealedCards[position]) {
imageView.setImageResource(images[position]) // Show the image
} else {
imageView.setImageResource(R.drawable.card_back) // Show the card back
}

return imageView
}

fun revealCard(position: Int) {


revealedCards[position] = true
}

fun hideCard(position: Int) {


revealedCards[position] = false
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<ImageView
android:id="@+id/resultImage"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:visibility="gone" />

<Button
android:id="@+id/actionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:visibility="gone"
android:layout_below="@id/resultImage"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="4"
android:horizontalSpacing="8dp"
android:verticalSpacing="8dp"
android:gravity="center"
android:layout_above="@id/resultImage"
android:padding="8dp" />
</RelativeLayout>
Practical 7 ( Quiz Game )
Main.kt

package com.example.quizapp

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private val questions = listOf(


Question("What is the capital of France?", listOf("Paris", "Berlin", "Madrid", "Rome"), 0),
Question("What is 5 + 3?", listOf("5", "8", "10", "15"), 1),
Question("Who wrote 'Romeo and Juliet'?", listOf("Shakespeare", "Hemingway", "Austen",
"Tolkien"), 0)
)

private var currentQuestionIndex = 0


private var score = 0

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val tvQuestion: TextView = findViewById(R.id.tvQuestion)


val rgOptions: RadioGroup = findViewById(R.id.rgOptions)
val btnSubmit: Button = findViewById(R.id.btnSubmit)
val tvFeedback: TextView = findViewById(R.id.tvFeedback)
val btnRetry: Button = findViewById(R.id.btnRetry)
val btnNext: Button = findViewById(R.id.btnNext)

fun loadQuestion() {
val question = questions[currentQuestionIndex]
tvQuestion.text = question.text

rgOptions.removeAllViews()
for ((index, option) in question.options.withIndex()) {
val radioButton = RadioButton(this)
radioButton.text = option
radioButton.id = index
rgOptions.addView(radioButton)
}

tvFeedback.text = ""
}

fun showResults() {
if (score >= 2) {
tvFeedback.text = "You passed! Score: $score/${questions.size}"
tvFeedback.setTextColor(getColor(android.R.color.holo_green_dark))
btnNext.visibility = Button.VISIBLE
btnRetry.visibility = Button.GONE
} else {
tvFeedback.text = "You failed. Score: $score/${questions.size}. Try again!"
tvFeedback.setTextColor(getColor(android.R.color.holo_red_dark))
btnRetry.visibility = Button.VISIBLE
btnNext.visibility = Button.GONE
}
btnSubmit.visibility = Button.GONE
}

btnSubmit.setOnClickListener {
val selectedOptionId = rgOptions.checkedRadioButtonId

if (selectedOptionId == -1) {
Toast.makeText(this, "Please select an option!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}

val question = questions[currentQuestionIndex]


if (selectedOptionId == question.correctOption) {
score++
}

currentQuestionIndex++
if (currentQuestionIndex < questions.size) {
loadQuestion()
} else {
showResults()
}
}

btnRetry.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Welcome back! Let's start again!"
loadQuestion()
}

btnNext.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Here’s your next quiz!"
loadQuestion()
}

loadQuestion()
}

data class Question(


val text: String,
val options: List<String>,
val correctOption: Int
)
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/tvQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to the Quiz!"
android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="16dp" />

<RadioGroup
android:id="@+id/rgOptions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />

<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp" />

<TextView
android:id="@+id/tvFeedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="16sp"
android:gravity="center"
android:layout_marginTop="16dp" />

<Button
android:id="@+id/btnRetry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retry"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />

<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Quiz"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />
</LinearLayout>

Practical 8 ( HeadTail )
Main.kt

package com.example.headtailgame

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import kotlin.random.Random

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Get references to UI elements


val coinImageView: ImageView = findViewById(R.id.coinImageView)
val resultTextView: TextView = findViewById(R.id.resultTextView)
val flipButton: Button = findViewById(R.id.flipButton)

// Handle button click


flipButton.setOnClickListener {
// Temporarily disable the button during the "flip"
flipButton.isEnabled = false
resultTextView.text = "Flipping..."

// Simulate a delay for randomness (e.g., 1 second)


Handler().postDelayed({
// Randomly choose between 0 (Head) and 1 (Tail)
val randomFlip = Random.nextInt(2)

// Update the ImageView and TextView based on the result


if (randomFlip == 0) {
coinImageView.setImageResource(R.drawable.f) // Head
resultTextView.text = "It's Head!"
} else {
coinImageView.setImageResource(R.drawable.b) // Tail
resultTextView.text = "It's Tail!"
}

// Re-enable the button after flipping


flipButton.isEnabled = true
}, 1000) // Delay for 1 second
}
}
}

Main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">

<!-- ImageView to display the coin -->


<ImageView
android:id="@+id/coinImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/f" />

<!-- TextView to display the flip result -->


<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip the coin!"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="16dp" />

<!-- Button to flip the coin -->


<Button
android:id="@+id/flipButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip Coin"
android:layout_marginTop="24dp" />

</LinearLayout>
Practical 1 ( Gridviewexample )
Main.kt

package com.example.gridviewexample

import android.os.Bundle
import android.widget.GridView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val gridView: GridView = findViewById(R.id.gridView)

// Create the list of items with titles and image resource IDs
var courseList = listOf<GridViewModal>()
courseList = courseList + GridViewModal("Tshirts", R.drawable.tshirts)
courseList = courseList + GridViewModal("Cap", R.drawable.cap)
courseList = courseList + GridViewModal("Shoes", R.drawable.shoes)
courseList = courseList + GridViewModal("Python", R.drawable.python)
courseList = courseList + GridViewModal("Javascript", R.drawable.js)

// Set up the adapter with the course list


val adapter = GridViewAdapter(this, courseList)
gridView.adapter = adapter
}
}

Adapter.kt

package com.example.gridviewexample

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView

data class GridViewModal(val title: String, val imageResId: Int)

class GridViewAdapter(private val context: Context, private val items: List<GridViewModal>) :


BaseAdapter() {
override fun getCount(): Int = items.size

override fun getItem(position: Int): Any = items[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val view: View = convertView ?: LayoutInflater.from(context).inflate(R.layout.grid_item, parent,
false)

// Bind image and title to the layout


val imageView: ImageView = view.findViewById(R.id.imageView)
val textView: TextView = view.findViewById(R.id.textView)

val item = items[position]


imageView.setImageResource(item.imageResId)
textView.text = item.title

return view
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" />
</RelativeLayout>

Grid.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="5dp">

<ImageView
android:id="@+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="centerCrop" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textColor="#000"
android:textSize="14sp"
android:gravity="center" />
</LinearLayout>

Practical 2 ( Radio Buttons )


Main.kt

package com.example.androidpractical2

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


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

// Input and Show Button


val editText = findViewById<EditText>(R.id.editText)
val buttonShowInput = findViewById<Button>(R.id.buttonShowInput)
buttonShowInput.setOnClickListener {
val inputText = editText.text.toString()
Toast.makeText(this, inputText, Toast.LENGTH_SHORT).show()
}

// RadioGroup and Get Color Button


val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
val buttonGetColor = findViewById<Button>(R.id.buttonGetColor)
buttonGetColor.setOnClickListener {
val selectedRadioId = radioGroup.checkedRadioButtonId
if (selectedRadioId != -1) {
val selectedRadioButton = findViewById<RadioButton>(selectedRadioId)
Toast.makeText(this, "Selected: ${selectedRadioButton.text}", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Please select a color", Toast.LENGTH_SHORT).show()
}
}

// Checkbox Button
val checkBoxCS = findViewById<CheckBox>(R.id.checkBoxCS)
val checkBoxIT = findViewById<CheckBox>(R.id.checkBoxIT)
val buttonSubmit = findViewById<Button>(R.id.buttonSubmit)
buttonSubmit.setOnClickListener {
val selectedOptions = mutableListOf<String>()
if (checkBoxCS.isChecked) selectedOptions.add("CS")
if (checkBoxIT.isChecked) selectedOptions.add("IT")
Toast.makeText(this, "Selected: ${selectedOptions.joinToString(", ")}",
Toast.LENGTH_SHORT).show()
}

// Spinner
val spinnerLanguage = findViewById<Spinner>(R.id.spinnerLanguage)
val languages = arrayOf("Java", "Kotlin", "C++", "Python")
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerLanguage.adapter = adapter

spinnerLanguage.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {


override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Toast.makeText(this@MainActivity, "Selected: ${languages[position]}",
Toast.LENGTH_SHORT).show()
}

override fun onNothingSelected(parent: AdapterView<*>?) {


// Do nothing
}
}
}
}

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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Input"
android:layout_margin="16dp"
android:inputType="text"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonShowInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Show Input"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/editText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonShowInput">

<TextView
android:id="@+id/radioGroupTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Which is your favorite color?"
android:textStyle="bold"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioYellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yellow"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioPink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pink"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioGreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green"
android:textColor="@android:color/white" />
</RadioGroup>

<Button
android:id="@+id/buttonGetColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Color"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toStartOf="@id/radioGroup"
app:layout_constraintTop_toBottomOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewDemo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView Demo"
android:textColor="@android:color/white"
app:layout_constraintTop_toTopOf="@id/radioGroup"
app:layout_constraintStart_toEndOf="@id/radioGroup"
app:layout_constraintEnd_toEndOf="parent" />

<CheckBox
android:id="@+id/checkBoxCS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CS"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/textViewDemo"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<CheckBox
android:id="@+id/checkBoxIT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IT"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/checkBoxCS"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/checkBoxIT"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Language"
android:textColor="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />

<Spinner
android:id="@+id/spinnerLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toEndOf="@id/textViewLanguage"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />
</androidx.constraintlayout.widget.ConstraintLayout>

Practical 3 ( Canva )
Main.kt

package com.example.canvas
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
class MainActivity : AppCompatActivity(), View.OnTouchListener {
// Declaring ImageView, Bitmap, Canvas, Paint,
// Down Coordinates and Up Coordinates
private lateinit var mImageView: ImageView
private lateinit var bitmap: Bitmap
private lateinit var canvas: Canvas
private lateinit var paint: Paint
private var downX = 0f
private var downY = 0f
private var upX = 0f
private var upY = 0f
@RequiresApi(Build.VERSION_CODES.R)
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initializing the ImageView
mImageView = findViewById(R.id.image_view_1)
// Getting the current window dimensions
val currentDisplay = windowManager.currentWindowMetrics
val dw = currentDisplay.bounds.width()
val dh = currentDisplay.bounds.height()
// Creating a bitmap with fetched dimensions
bitmap = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888)
// Storing the canvas on the bitmap
canvas = Canvas(bitmap)
// Initializing Paint to determine
// stoke attributes like color and size
paint = Paint()
paint.color = Color.RED
paint.strokeWidth = 10F
// Setting the bitmap on ImageView
mImageView.setImageBitmap(bitmap)
// Setting onTouchListener on the ImageView
mImageView.setOnTouchListener(this)
}
// When Touch is detected on the ImageView,
// Initial and final coordinates are recorded
// and a line is drawn between them.
// ImagView is updated
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
when (event!!.action) {
MotionEvent.ACTION_DOWN -> {
downX = event.x
downY = event.y
}
MotionEvent.ACTION_UP -> {
upX = event.x
upY = event.y
canvas.drawLine(downX, downY, upX, upY, paint)
mImageView.invalidate()
}
}
return true
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
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:id="@+id/image_view_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="ContentDescription"
android:background="@color/black"/>
</RelativeLayout>
Practical 4 ( Caculator )
Main.kt

package com.example.calculator

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val etNumber1: EditText = findViewById(R.id.etNumber1)


val etNumber2: EditText = findViewById(R.id.etNumber2)
val btnAdd: Button = findViewById(R.id.btnAdd)
val btnSubtract: Button = findViewById(R.id.btnSubtract)
val btnMultiply: Button = findViewById(R.id.btnMultiply)
val btnDivide: Button = findViewById(R.id.btnDivide)
val tvResult: TextView = findViewById(R.id.tvResult)

btnAdd.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "add")
}

btnSubtract.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "subtract")
}

btnMultiply.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "multiply")
}

btnDivide.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "divide")
}
}

private fun calculate(etNumber1: EditText, etNumber2: EditText, tvResult: TextView, operation:


String) {
val number1 = etNumber1.text.toString()
val number2 = etNumber2.text.toString()
if (number1.isEmpty() || number2.isEmpty()) {
Toast.makeText(this, "Please enter both numbers", Toast.LENGTH_SHORT).show()
return
}

val num1 = number1.toDouble()


val num2 = number2.toDouble()
val result = when (operation) {
"add" -> num1 + num2
"subtract" -> num1 - num2
"multiply" -> num1 * num2
"divide" -> {
if (num2 == 0.0) {
Toast.makeText(this, "Cannot divide by zero", Toast.LENGTH_SHORT).show()
return
} else {
num1 / num2
}
}
else -> 0.0
}
tvResult.text = "Result: $result"
}
}

main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/etNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal"
android:layout_marginBottom="8dp"/>

<EditText
android:id="@+id/etNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal"
android:layout_marginBottom="16dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">

<Button
android:id="@+id/btnAdd"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="+" />

<Button
android:id="@+id/btnSubtract"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="-" />

<Button
android:id="@+id/btnMultiply"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="*" />

<Button
android:id="@+id/btnDivide"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="/" />
</LinearLayout>

<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Result: "
android:textSize="18sp"
android:textStyle="bold" />

</LinearLayout>
Prcatical 5 ( ImageFlliper )
Main.kt

package com.example.imageflipper

import android.os.Bundle
import android.widget.Button
import android.widget.ViewFlipper
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Reference to ViewFlipper
val viewFlipper: ViewFlipper = findViewById(R.id.viewFlipper)

// Reference to buttons
val nextButton: Button = findViewById(R.id.buttonNext)
val prevButton: Button = findViewById(R.id.buttonPrev)

// Next button click listener


nextButton.setOnClickListener {
viewFlipper.showNext()
}

// Previous button click listener


prevButton.setOnClickListener {
viewFlipper.showPrevious()
}
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<!-- ViewFlipper to flip images -->


<ViewFlipper
android:id="@+id/viewFlipper"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_centerInParent="true">

<!-- Add images for flipping -->


<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/shoes"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/cap"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/tshirts"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/pokemon"
android:scaleType="centerCrop" />
</ViewFlipper>

<!-- Buttons to navigate -->


<Button
android:id="@+id/buttonPrev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />

<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />
</RelativeLayout>
Prcatical 6 ( MemoryGame )
Main.kt

package com.example.memorygame

import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var gridView: GridView


private lateinit var imageAdapter: ImageAdapter
private lateinit var resultImage: ImageView
private lateinit var actionButton: Button
private val handler = Handler()

// Images and game logic


private val images = arrayOf(
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon,
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon
)
private var shuffledImages = images.toList().shuffled()
private var firstCardIndex = -1
private var secondCardIndex = -1
private var score = 0
private var wrongFlips = 0
private val maxWrongFlips = 4
private var flippedCards = mutableSetOf<Int>()

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

gridView = findViewById(R.id.gridView)
resultImage = findViewById(R.id.resultImage)
actionButton = findViewById(R.id.actionButton)

startGame()

actionButton.setOnClickListener {
resetGame()
}

gridView.setOnItemClickListener { _, _, position, _ ->


if (flippedCards.contains(position) || firstCardIndex == position || wrongFlips >=
maxWrongFlips) {
return@setOnItemClickListener
}

// Flip the card


imageAdapter.revealCard(position)
imageAdapter.notifyDataSetChanged()

if (firstCardIndex == -1) {
// First card selected
firstCardIndex = position
} else if (secondCardIndex == -1) {
// Second card selected
secondCardIndex = position

// Check for match


checkForMatch()
}
}
}

private fun startGame() {


shuffledImages = images.toList().shuffled()
imageAdapter = ImageAdapter(this, shuffledImages)
gridView.adapter = imageAdapter

// Reset variables
firstCardIndex = -1
secondCardIndex = -1
score = 0
wrongFlips = 0
flippedCards.clear()

// Hide result image and button


resultImage.visibility = View.GONE
actionButton.visibility = View.GONE
gridView.visibility = View.VISIBLE
}

private fun checkForMatch() {


handler.postDelayed({
if (shuffledImages[firstCardIndex] == shuffledImages[secondCardIndex]) {
// Cards match
flippedCards.add(firstCardIndex)
flippedCards.add(secondCardIndex)
score += 1

// Check for game completion


if (flippedCards.size == shuffledImages.size) {
showWin()
}
} else {
// Cards don't match, hide them and increment wrong flip count
imageAdapter.hideCard(firstCardIndex)
imageAdapter.hideCard(secondCardIndex)
wrongFlips += 1

if (wrongFlips >= maxWrongFlips) {


showFailure()
}
}

// Reset selection
firstCardIndex = -1
secondCardIndex = -1
imageAdapter.notifyDataSetChanged()
}, 1000)
}

private fun showWin() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.happy)
resultImage.visibility = View.VISIBLE
actionButton.text = "Reset"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Win!", Toast.LENGTH_SHORT).show()
}

private fun showFailure() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.failed)
resultImage.visibility = View.VISIBLE
actionButton.text = "Retry"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Failed! Retry the game.", Toast.LENGTH_SHORT).show()
}

private fun resetGame() {


startGame()
Toast.makeText(this, "Game Reset! Good luck!", Toast.LENGTH_SHORT).show()
}
}

ImageAdapter.kt
package com.example.memorygame

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView

class ImageAdapter(private val context: Context, private val images: List<Int>) : BaseAdapter() {

private val revealedCards = BooleanArray(images.size)

override fun getCount(): Int = images.size

override fun getItem(position: Int): Any = images[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val imageView: ImageView = convertView as? ImageView ?: ImageView(context)

imageView.layoutParams = ViewGroup.LayoutParams(200, 200)


imageView.scaleType = ImageView.ScaleType.CENTER_CROP
imageView.setPadding(8, 8, 8, 8)

if (revealedCards[position]) {
imageView.setImageResource(images[position]) // Show the image
} else {
imageView.setImageResource(R.drawable.card_back) // Show the card back
}

return imageView
}

fun revealCard(position: Int) {


revealedCards[position] = true
}

fun hideCard(position: Int) {


revealedCards[position] = false
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<ImageView
android:id="@+id/resultImage"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:visibility="gone" />

<Button
android:id="@+id/actionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:visibility="gone"
android:layout_below="@id/resultImage"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="4"
android:horizontalSpacing="8dp"
android:verticalSpacing="8dp"
android:gravity="center"
android:layout_above="@id/resultImage"
android:padding="8dp" />
</RelativeLayout>
Practical 7 ( Quiz Game )
Main.kt

package com.example.quizapp

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private val questions = listOf(


Question("What is the capital of France?", listOf("Paris", "Berlin", "Madrid", "Rome"), 0),
Question("What is 5 + 3?", listOf("5", "8", "10", "15"), 1),
Question("Who wrote 'Romeo and Juliet'?", listOf("Shakespeare", "Hemingway", "Austen",
"Tolkien"), 0)
)

private var currentQuestionIndex = 0


private var score = 0

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val tvQuestion: TextView = findViewById(R.id.tvQuestion)


val rgOptions: RadioGroup = findViewById(R.id.rgOptions)
val btnSubmit: Button = findViewById(R.id.btnSubmit)
val tvFeedback: TextView = findViewById(R.id.tvFeedback)
val btnRetry: Button = findViewById(R.id.btnRetry)
val btnNext: Button = findViewById(R.id.btnNext)

fun loadQuestion() {
val question = questions[currentQuestionIndex]
tvQuestion.text = question.text

rgOptions.removeAllViews()
for ((index, option) in question.options.withIndex()) {
val radioButton = RadioButton(this)
radioButton.text = option
radioButton.id = index
rgOptions.addView(radioButton)
}

tvFeedback.text = ""
}

fun showResults() {
if (score >= 2) {
tvFeedback.text = "You passed! Score: $score/${questions.size}"
tvFeedback.setTextColor(getColor(android.R.color.holo_green_dark))
btnNext.visibility = Button.VISIBLE
btnRetry.visibility = Button.GONE
} else {
tvFeedback.text = "You failed. Score: $score/${questions.size}. Try again!"
tvFeedback.setTextColor(getColor(android.R.color.holo_red_dark))
btnRetry.visibility = Button.VISIBLE
btnNext.visibility = Button.GONE
}
btnSubmit.visibility = Button.GONE
}

btnSubmit.setOnClickListener {
val selectedOptionId = rgOptions.checkedRadioButtonId

if (selectedOptionId == -1) {
Toast.makeText(this, "Please select an option!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}

val question = questions[currentQuestionIndex]


if (selectedOptionId == question.correctOption) {
score++
}

currentQuestionIndex++
if (currentQuestionIndex < questions.size) {
loadQuestion()
} else {
showResults()
}
}

btnRetry.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Welcome back! Let's start again!"
loadQuestion()
}

btnNext.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Here’s your next quiz!"
loadQuestion()
}

loadQuestion()
}

data class Question(


val text: String,
val options: List<String>,
val correctOption: Int
)
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/tvQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to the Quiz!"
android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="16dp" />

<RadioGroup
android:id="@+id/rgOptions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />

<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp" />

<TextView
android:id="@+id/tvFeedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="16sp"
android:gravity="center"
android:layout_marginTop="16dp" />

<Button
android:id="@+id/btnRetry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retry"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />

<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Quiz"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />
</LinearLayout>

Practical 8 ( HeadTail )
Main.kt

package com.example.headtailgame

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import kotlin.random.Random

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Get references to UI elements


val coinImageView: ImageView = findViewById(R.id.coinImageView)
val resultTextView: TextView = findViewById(R.id.resultTextView)
val flipButton: Button = findViewById(R.id.flipButton)

// Handle button click


flipButton.setOnClickListener {
// Temporarily disable the button during the "flip"
flipButton.isEnabled = false
resultTextView.text = "Flipping..."

// Simulate a delay for randomness (e.g., 1 second)


Handler().postDelayed({
// Randomly choose between 0 (Head) and 1 (Tail)
val randomFlip = Random.nextInt(2)

// Update the ImageView and TextView based on the result


if (randomFlip == 0) {
coinImageView.setImageResource(R.drawable.f) // Head
resultTextView.text = "It's Head!"
} else {
coinImageView.setImageResource(R.drawable.b) // Tail
resultTextView.text = "It's Tail!"
}

// Re-enable the button after flipping


flipButton.isEnabled = true
}, 1000) // Delay for 1 second
}
}
}

Main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">

<!-- ImageView to display the coin -->


<ImageView
android:id="@+id/coinImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/f" />

<!-- TextView to display the flip result -->


<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip the coin!"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="16dp" />

<!-- Button to flip the coin -->


<Button
android:id="@+id/flipButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip Coin"
android:layout_marginTop="24dp" />

</LinearLayout>
Practical 1 ( Gridviewexample )
Main.kt

package com.example.gridviewexample

import android.os.Bundle
import android.widget.GridView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val gridView: GridView = findViewById(R.id.gridView)

// Create the list of items with titles and image resource IDs
var courseList = listOf<GridViewModal>()
courseList = courseList + GridViewModal("Tshirts", R.drawable.tshirts)
courseList = courseList + GridViewModal("Cap", R.drawable.cap)
courseList = courseList + GridViewModal("Shoes", R.drawable.shoes)
courseList = courseList + GridViewModal("Python", R.drawable.python)
courseList = courseList + GridViewModal("Javascript", R.drawable.js)

// Set up the adapter with the course list


val adapter = GridViewAdapter(this, courseList)
gridView.adapter = adapter
}
}

Adapter.kt

package com.example.gridviewexample

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView

data class GridViewModal(val title: String, val imageResId: Int)

class GridViewAdapter(private val context: Context, private val items: List<GridViewModal>) :


BaseAdapter() {
override fun getCount(): Int = items.size

override fun getItem(position: Int): Any = items[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val view: View = convertView ?: LayoutInflater.from(context).inflate(R.layout.grid_item, parent,
false)

// Bind image and title to the layout


val imageView: ImageView = view.findViewById(R.id.imageView)
val textView: TextView = view.findViewById(R.id.textView)

val item = items[position]


imageView.setImageResource(item.imageResId)
textView.text = item.title

return view
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" />
</RelativeLayout>

Grid.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="5dp">

<ImageView
android:id="@+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="centerCrop" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textColor="#000"
android:textSize="14sp"
android:gravity="center" />
</LinearLayout>

Practical 2 ( Radio Buttons )


Main.kt

package com.example.androidpractical2

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


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

// Input and Show Button


val editText = findViewById<EditText>(R.id.editText)
val buttonShowInput = findViewById<Button>(R.id.buttonShowInput)
buttonShowInput.setOnClickListener {
val inputText = editText.text.toString()
Toast.makeText(this, inputText, Toast.LENGTH_SHORT).show()
}

// RadioGroup and Get Color Button


val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
val buttonGetColor = findViewById<Button>(R.id.buttonGetColor)
buttonGetColor.setOnClickListener {
val selectedRadioId = radioGroup.checkedRadioButtonId
if (selectedRadioId != -1) {
val selectedRadioButton = findViewById<RadioButton>(selectedRadioId)
Toast.makeText(this, "Selected: ${selectedRadioButton.text}", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Please select a color", Toast.LENGTH_SHORT).show()
}
}

// Checkbox Button
val checkBoxCS = findViewById<CheckBox>(R.id.checkBoxCS)
val checkBoxIT = findViewById<CheckBox>(R.id.checkBoxIT)
val buttonSubmit = findViewById<Button>(R.id.buttonSubmit)
buttonSubmit.setOnClickListener {
val selectedOptions = mutableListOf<String>()
if (checkBoxCS.isChecked) selectedOptions.add("CS")
if (checkBoxIT.isChecked) selectedOptions.add("IT")
Toast.makeText(this, "Selected: ${selectedOptions.joinToString(", ")}",
Toast.LENGTH_SHORT).show()
}

// Spinner
val spinnerLanguage = findViewById<Spinner>(R.id.spinnerLanguage)
val languages = arrayOf("Java", "Kotlin", "C++", "Python")
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerLanguage.adapter = adapter

spinnerLanguage.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {


override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Toast.makeText(this@MainActivity, "Selected: ${languages[position]}",
Toast.LENGTH_SHORT).show()
}

override fun onNothingSelected(parent: AdapterView<*>?) {


// Do nothing
}
}
}
}

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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Input"
android:layout_margin="16dp"
android:inputType="text"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonShowInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Show Input"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/editText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonShowInput">

<TextView
android:id="@+id/radioGroupTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Which is your favorite color?"
android:textStyle="bold"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioYellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yellow"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioPink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pink"
android:textColor="@android:color/white" />

<RadioButton
android:id="@+id/radioGreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green"
android:textColor="@android:color/white" />
</RadioGroup>

<Button
android:id="@+id/buttonGetColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Color"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toStartOf="@id/radioGroup"
app:layout_constraintTop_toBottomOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewDemo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView Demo"
android:textColor="@android:color/white"
app:layout_constraintTop_toTopOf="@id/radioGroup"
app:layout_constraintStart_toEndOf="@id/radioGroup"
app:layout_constraintEnd_toEndOf="parent" />

<CheckBox
android:id="@+id/checkBoxCS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CS"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/textViewDemo"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<CheckBox
android:id="@+id/checkBoxIT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IT"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@id/checkBoxCS"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@android:color/white"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintTop_toBottomOf="@id/checkBoxIT"
app:layout_constraintStart_toEndOf="@id/radioGroup" />

<TextView
android:id="@+id/textViewLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Language"
android:textColor="@android:color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />

<Spinner
android:id="@+id/spinnerLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@android:color/darker_gray"
app:layout_constraintStart_toEndOf="@id/textViewLanguage"
app:layout_constraintTop_toBottomOf="@id/buttonGetColor" />
</androidx.constraintlayout.widget.ConstraintLayout>

Practical 3 ( Canva )
Main.kt

package com.example.canvas
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
class MainActivity : AppCompatActivity(), View.OnTouchListener {
// Declaring ImageView, Bitmap, Canvas, Paint,
// Down Coordinates and Up Coordinates
private lateinit var mImageView: ImageView
private lateinit var bitmap: Bitmap
private lateinit var canvas: Canvas
private lateinit var paint: Paint
private var downX = 0f
private var downY = 0f
private var upX = 0f
private var upY = 0f
@RequiresApi(Build.VERSION_CODES.R)
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initializing the ImageView
mImageView = findViewById(R.id.image_view_1)
// Getting the current window dimensions
val currentDisplay = windowManager.currentWindowMetrics
val dw = currentDisplay.bounds.width()
val dh = currentDisplay.bounds.height()
// Creating a bitmap with fetched dimensions
bitmap = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888)
// Storing the canvas on the bitmap
canvas = Canvas(bitmap)
// Initializing Paint to determine
// stoke attributes like color and size
paint = Paint()
paint.color = Color.RED
paint.strokeWidth = 10F
// Setting the bitmap on ImageView
mImageView.setImageBitmap(bitmap)
// Setting onTouchListener on the ImageView
mImageView.setOnTouchListener(this)
}
// When Touch is detected on the ImageView,
// Initial and final coordinates are recorded
// and a line is drawn between them.
// ImagView is updated
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
when (event!!.action) {
MotionEvent.ACTION_DOWN -> {
downX = event.x
downY = event.y
}
MotionEvent.ACTION_UP -> {
upX = event.x
upY = event.y
canvas.drawLine(downX, downY, upX, upY, paint)
mImageView.invalidate()
}
}
return true
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
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:id="@+id/image_view_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="ContentDescription"
android:background="@color/black"/>
</RelativeLayout>
Practical 4 ( Caculator )
Main.kt

package com.example.calculator

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val etNumber1: EditText = findViewById(R.id.etNumber1)


val etNumber2: EditText = findViewById(R.id.etNumber2)
val btnAdd: Button = findViewById(R.id.btnAdd)
val btnSubtract: Button = findViewById(R.id.btnSubtract)
val btnMultiply: Button = findViewById(R.id.btnMultiply)
val btnDivide: Button = findViewById(R.id.btnDivide)
val tvResult: TextView = findViewById(R.id.tvResult)

btnAdd.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "add")
}

btnSubtract.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "subtract")
}

btnMultiply.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "multiply")
}

btnDivide.setOnClickListener {
calculate(etNumber1, etNumber2, tvResult, "divide")
}
}

private fun calculate(etNumber1: EditText, etNumber2: EditText, tvResult: TextView, operation:


String) {
val number1 = etNumber1.text.toString()
val number2 = etNumber2.text.toString()
if (number1.isEmpty() || number2.isEmpty()) {
Toast.makeText(this, "Please enter both numbers", Toast.LENGTH_SHORT).show()
return
}

val num1 = number1.toDouble()


val num2 = number2.toDouble()
val result = when (operation) {
"add" -> num1 + num2
"subtract" -> num1 - num2
"multiply" -> num1 * num2
"divide" -> {
if (num2 == 0.0) {
Toast.makeText(this, "Cannot divide by zero", Toast.LENGTH_SHORT).show()
return
} else {
num1 / num2
}
}
else -> 0.0
}
tvResult.text = "Result: $result"
}
}

main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/etNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal"
android:layout_marginBottom="8dp"/>

<EditText
android:id="@+id/etNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal"
android:layout_marginBottom="16dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">

<Button
android:id="@+id/btnAdd"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="+" />

<Button
android:id="@+id/btnSubtract"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="-" />

<Button
android:id="@+id/btnMultiply"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="*" />

<Button
android:id="@+id/btnDivide"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="/" />
</LinearLayout>

<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Result: "
android:textSize="18sp"
android:textStyle="bold" />

</LinearLayout>
Prcatical 5 ( ImageFlliper )
Main.kt

package com.example.imageflipper

import android.os.Bundle
import android.widget.Button
import android.widget.ViewFlipper
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Reference to ViewFlipper
val viewFlipper: ViewFlipper = findViewById(R.id.viewFlipper)

// Reference to buttons
val nextButton: Button = findViewById(R.id.buttonNext)
val prevButton: Button = findViewById(R.id.buttonPrev)

// Next button click listener


nextButton.setOnClickListener {
viewFlipper.showNext()
}

// Previous button click listener


prevButton.setOnClickListener {
viewFlipper.showPrevious()
}
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<!-- ViewFlipper to flip images -->


<ViewFlipper
android:id="@+id/viewFlipper"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_centerInParent="true">

<!-- Add images for flipping -->


<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/shoes"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/cap"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/tshirts"
android:scaleType="centerCrop" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/pokemon"
android:scaleType="centerCrop" />
</ViewFlipper>

<!-- Buttons to navigate -->


<Button
android:id="@+id/buttonPrev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />

<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp" />
</RelativeLayout>
Prcatical 6 ( MemoryGame )
Main.kt

package com.example.memorygame

import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var gridView: GridView


private lateinit var imageAdapter: ImageAdapter
private lateinit var resultImage: ImageView
private lateinit var actionButton: Button
private val handler = Handler()

// Images and game logic


private val images = arrayOf(
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon,
R.drawable.shoes, R.drawable.cap, R.drawable.tshirts, R.drawable.pokemon
)
private var shuffledImages = images.toList().shuffled()
private var firstCardIndex = -1
private var secondCardIndex = -1
private var score = 0
private var wrongFlips = 0
private val maxWrongFlips = 4
private var flippedCards = mutableSetOf<Int>()

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

gridView = findViewById(R.id.gridView)
resultImage = findViewById(R.id.resultImage)
actionButton = findViewById(R.id.actionButton)

startGame()

actionButton.setOnClickListener {
resetGame()
}

gridView.setOnItemClickListener { _, _, position, _ ->


if (flippedCards.contains(position) || firstCardIndex == position || wrongFlips >=
maxWrongFlips) {
return@setOnItemClickListener
}

// Flip the card


imageAdapter.revealCard(position)
imageAdapter.notifyDataSetChanged()

if (firstCardIndex == -1) {
// First card selected
firstCardIndex = position
} else if (secondCardIndex == -1) {
// Second card selected
secondCardIndex = position

// Check for match


checkForMatch()
}
}
}

private fun startGame() {


shuffledImages = images.toList().shuffled()
imageAdapter = ImageAdapter(this, shuffledImages)
gridView.adapter = imageAdapter

// Reset variables
firstCardIndex = -1
secondCardIndex = -1
score = 0
wrongFlips = 0
flippedCards.clear()

// Hide result image and button


resultImage.visibility = View.GONE
actionButton.visibility = View.GONE
gridView.visibility = View.VISIBLE
}

private fun checkForMatch() {


handler.postDelayed({
if (shuffledImages[firstCardIndex] == shuffledImages[secondCardIndex]) {
// Cards match
flippedCards.add(firstCardIndex)
flippedCards.add(secondCardIndex)
score += 1

// Check for game completion


if (flippedCards.size == shuffledImages.size) {
showWin()
}
} else {
// Cards don't match, hide them and increment wrong flip count
imageAdapter.hideCard(firstCardIndex)
imageAdapter.hideCard(secondCardIndex)
wrongFlips += 1

if (wrongFlips >= maxWrongFlips) {


showFailure()
}
}

// Reset selection
firstCardIndex = -1
secondCardIndex = -1
imageAdapter.notifyDataSetChanged()
}, 1000)
}

private fun showWin() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.happy)
resultImage.visibility = View.VISIBLE
actionButton.text = "Reset"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Win!", Toast.LENGTH_SHORT).show()
}

private fun showFailure() {


gridView.visibility = View.GONE
resultImage.setImageResource(R.drawable.failed)
resultImage.visibility = View.VISIBLE
actionButton.text = "Retry"
actionButton.visibility = View.VISIBLE
Toast.makeText(this, "You Failed! Retry the game.", Toast.LENGTH_SHORT).show()
}

private fun resetGame() {


startGame()
Toast.makeText(this, "Game Reset! Good luck!", Toast.LENGTH_SHORT).show()
}
}

ImageAdapter.kt
package com.example.memorygame

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView

class ImageAdapter(private val context: Context, private val images: List<Int>) : BaseAdapter() {

private val revealedCards = BooleanArray(images.size)

override fun getCount(): Int = images.size

override fun getItem(position: Int): Any = images[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {


val imageView: ImageView = convertView as? ImageView ?: ImageView(context)

imageView.layoutParams = ViewGroup.LayoutParams(200, 200)


imageView.scaleType = ImageView.ScaleType.CENTER_CROP
imageView.setPadding(8, 8, 8, 8)

if (revealedCards[position]) {
imageView.setImageResource(images[position]) // Show the image
} else {
imageView.setImageResource(R.drawable.card_back) // Show the card back
}

return imageView
}

fun revealCard(position: Int) {


revealedCards[position] = true
}

fun hideCard(position: Int) {


revealedCards[position] = false
}
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<ImageView
android:id="@+id/resultImage"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:visibility="gone" />

<Button
android:id="@+id/actionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:visibility="gone"
android:layout_below="@id/resultImage"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="4"
android:horizontalSpacing="8dp"
android:verticalSpacing="8dp"
android:gravity="center"
android:layout_above="@id/resultImage"
android:padding="8dp" />
</RelativeLayout>
Practical 7 ( Quiz Game )
Main.kt

package com.example.quizapp

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private val questions = listOf(


Question("What is the capital of France?", listOf("Paris", "Berlin", "Madrid", "Rome"), 0),
Question("What is 5 + 3?", listOf("5", "8", "10", "15"), 1),
Question("Who wrote 'Romeo and Juliet'?", listOf("Shakespeare", "Hemingway", "Austen",
"Tolkien"), 0)
)

private var currentQuestionIndex = 0


private var score = 0

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val tvQuestion: TextView = findViewById(R.id.tvQuestion)


val rgOptions: RadioGroup = findViewById(R.id.rgOptions)
val btnSubmit: Button = findViewById(R.id.btnSubmit)
val tvFeedback: TextView = findViewById(R.id.tvFeedback)
val btnRetry: Button = findViewById(R.id.btnRetry)
val btnNext: Button = findViewById(R.id.btnNext)

fun loadQuestion() {
val question = questions[currentQuestionIndex]
tvQuestion.text = question.text

rgOptions.removeAllViews()
for ((index, option) in question.options.withIndex()) {
val radioButton = RadioButton(this)
radioButton.text = option
radioButton.id = index
rgOptions.addView(radioButton)
}

tvFeedback.text = ""
}

fun showResults() {
if (score >= 2) {
tvFeedback.text = "You passed! Score: $score/${questions.size}"
tvFeedback.setTextColor(getColor(android.R.color.holo_green_dark))
btnNext.visibility = Button.VISIBLE
btnRetry.visibility = Button.GONE
} else {
tvFeedback.text = "You failed. Score: $score/${questions.size}. Try again!"
tvFeedback.setTextColor(getColor(android.R.color.holo_red_dark))
btnRetry.visibility = Button.VISIBLE
btnNext.visibility = Button.GONE
}
btnSubmit.visibility = Button.GONE
}

btnSubmit.setOnClickListener {
val selectedOptionId = rgOptions.checkedRadioButtonId

if (selectedOptionId == -1) {
Toast.makeText(this, "Please select an option!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}

val question = questions[currentQuestionIndex]


if (selectedOptionId == question.correctOption) {
score++
}

currentQuestionIndex++
if (currentQuestionIndex < questions.size) {
loadQuestion()
} else {
showResults()
}
}

btnRetry.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Welcome back! Let's start again!"
loadQuestion()
}

btnNext.setOnClickListener {
score = 0
currentQuestionIndex = 0
btnRetry.visibility = Button.GONE
btnNext.visibility = Button.GONE
btnSubmit.visibility = Button.VISIBLE
tvFeedback.text = "Here’s your next quiz!"
loadQuestion()
}

loadQuestion()
}

data class Question(


val text: String,
val options: List<String>,
val correctOption: Int
)
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/tvQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to the Quiz!"
android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="16dp" />

<RadioGroup
android:id="@+id/rgOptions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />

<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp" />

<TextView
android:id="@+id/tvFeedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="16sp"
android:gravity="center"
android:layout_marginTop="16dp" />

<Button
android:id="@+id/btnRetry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retry"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />

<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Quiz"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:visibility="gone" />
</LinearLayout>

Practical 8 ( HeadTail )
Main.kt

package com.example.headtailgame

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import kotlin.random.Random

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Get references to UI elements


val coinImageView: ImageView = findViewById(R.id.coinImageView)
val resultTextView: TextView = findViewById(R.id.resultTextView)
val flipButton: Button = findViewById(R.id.flipButton)

// Handle button click


flipButton.setOnClickListener {
// Temporarily disable the button during the "flip"
flipButton.isEnabled = false
resultTextView.text = "Flipping..."

// Simulate a delay for randomness (e.g., 1 second)


Handler().postDelayed({
// Randomly choose between 0 (Head) and 1 (Tail)
val randomFlip = Random.nextInt(2)

// Update the ImageView and TextView based on the result


if (randomFlip == 0) {
coinImageView.setImageResource(R.drawable.f) // Head
resultTextView.text = "It's Head!"
} else {
coinImageView.setImageResource(R.drawable.b) // Tail
resultTextView.text = "It's Tail!"
}

// Re-enable the button after flipping


flipButton.isEnabled = true
}, 1000) // Delay for 1 second
}
}
}

Main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">

<!-- ImageView to display the coin -->


<ImageView
android:id="@+id/coinImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/f" />

<!-- TextView to display the flip result -->


<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip the coin!"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="16dp" />

<!-- Button to flip the coin -->


<Button
android:id="@+id/flipButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flip Coin"
android:layout_marginTop="24dp" />

</LinearLayout>

You might also like