Advertisement
Guest User

Untitled

a guest
Jan 27th, 2021
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.61 KB | None | 0 0
  1. class MainActivity : AppCompatActivity() {
  2.     private val TAG = MainActivity::class.java.simpleName
  3.  
  4.     override fun onCreate(savedInstanceState: Bundle?) {
  5.         super.onCreate(savedInstanceState)
  6.         setContentView(R.layout.activity_main)
  7.  
  8.         val roll = findViewById<Button>(R.id.button_roll)
  9.  
  10.         roll.setOnClickListener {
  11.             Toast.makeText(this, "Dice Rolled", Toast.LENGTH_SHORT).show()
  12.             rollDice()
  13.  
  14.         }
  15.  
  16.         if (savedInstanceState != null) {
  17.             val saveImage = savedInstanceState.getInt("drawableRes")
  18.             imageView.setImageResource(saveImage)
  19.         }
  20.  
  21.     }
  22.  
  23.  
  24.     private fun rollDice() {
  25.  
  26.        
  27.         val dice = Dice(6)
  28.         val diceRoll = dice.roll()
  29.  
  30.        
  31.         val diceImage = findViewById<ImageView>(R.id.imageView)
  32.  
  33.        
  34.         val diceResource = when (dice.roll()) {
  35.             1 -> R.drawable.dice_1
  36.             2 -> R.drawable.dice_2
  37.             3 -> R.drawable.dice_3
  38.             4 -> R.drawable.dice_4
  39.             5 -> R.drawable.dice_5
  40.             else -> R.drawable.dice_6
  41.         }
  42.  
  43.         diceImage.apply {
  44.             setImageResource(diceResource)
  45.             tag = diceResource
  46.             contentDescription = diceRoll.toString()
  47.         }
  48.     }
  49.  
  50.     override fun onSaveInstanceState(outState: Bundle) {
  51.         super.onSaveInstanceState(outState)
  52.         Log.d(TAG, "onSaveInstanceState: ${imageView.tag}")
  53.         //outState.putInt("drawableRes", )
  54.     }
  55. }
  56.  
  57. class Dice(private val numSide: Int) {
  58.     fun roll(): Int {
  59.         return (1..numSide).random()
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement