Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MainActivity : AppCompatActivity() {
- private val TAG = MainActivity::class.java.simpleName
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- val roll = findViewById<Button>(R.id.button_roll)
- roll.setOnClickListener {
- Toast.makeText(this, "Dice Rolled", Toast.LENGTH_SHORT).show()
- rollDice()
- }
- if (savedInstanceState != null) {
- val saveImage = savedInstanceState.getInt("drawableRes")
- imageView.setImageResource(saveImage)
- }
- }
- private fun rollDice() {
- val dice = Dice(6)
- val diceRoll = dice.roll()
- val diceImage = findViewById<ImageView>(R.id.imageView)
- val diceResource = when (dice.roll()) {
- 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
- }
- diceImage.apply {
- setImageResource(diceResource)
- tag = diceResource
- contentDescription = diceRoll.toString()
- }
- }
- override fun onSaveInstanceState(outState: Bundle) {
- super.onSaveInstanceState(outState)
- Log.d(TAG, "onSaveInstanceState: ${imageView.tag}")
- //outState.putInt("drawableRes", )
- }
- }
- class Dice(private val numSide: Int) {
- fun roll(): Int {
- return (1..numSide).random()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement