Dice Roller application that has a button to roll a dice and update the image on the screen
Thu Oct 31 2024 09:56:54 GMT+0000 (Coordinated Universal Time)
Saved by
@carona
7. Create a Dice Roller application that has a button to roll a dice and update the image on the screen.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/dice_1" />
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ROLL"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/iv" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.example.roll_dice
//import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
class MainActivity : AppCompatActivity() {
// @SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btn:Button=findViewById(R.id.b1)
btn.setOnClickListener {
rollDice()
}
}
private fun rollDice(){
val dice=Dice(6)
val diceRoll=dice.roll()
val imgv:ImageView=findViewById(R.id.iv)
val drawableResource=when(diceRoll){
1->R.drawable.dice_1
2->R.drawable.dice_2
3->R.drawable.dice_3
4->R.drawable.dice_4
5->R.drawable.dice_5
else->R.drawable.dice_6
}
imgv.setImageResource(drawableResource)
}
}
class Dice(private val numSides:Int){
fun roll():Int{
return (1..numSides).random()
}
}
content_copyCOPY
Comments