MainActivity: package com.cscorner.myapplication2 import android.os.Bundle import android.widget.Button import android.widget.ImageView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main) val button: Button=findViewById(R.id.button) button.setOnClickListener{ rollDice() } } private fun rollDice(){ val dice=Dice(6) val diceRoll=dice.roll() val img :ImageView=findViewById(R.id.imageView) val drawableResource = when(diceRoll){ 1->R.drawable.dice1 2->R.drawable.dice2 3->R.drawable.dice3 4->R.drawable.dice4 5->R.drawable.dice5 else->R.drawable.dice5 } img.setImageResource(drawableResource) } } class Dice(private val numsides:Int){ fun roll():Int{ return (1..numsides).random() } } 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/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.5" tools:srcCompat="@drawable/dice_1" /> <Button android:id="@+id/button" 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_toTopOf="parent" app:layout_constraintVertical_bias="0.775" /> </androidx.constraintlayout.widget.ConstraintLayout>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter