用kotlin语言在AndroidStudio上实现点击按钮随机出现骰子点数并显示和的代码
时间: 2023-03-31 13:04:55 浏览: 104
您好,以下是用 Kotlin 语言在 Android Studio 上实现点击按钮随机出现骰子点数并显示和的代码:
1. 在 XML 布局文件中添加一个 Button 和一个 TextView:
```
<Button
android:id="@+id/roll_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Roll the Dice" />
<TextView
android:id="@+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="36sp" />
```
2. 在 Kotlin 代码中,为 Button 添加点击事件,并在事件中生成随机数并计算和:
```
val rollButton: Button = findViewById(R.id.roll_button)
val resultText: TextView = findViewById(R.id.result_text)
rollButton.setOnClickListener {
val randomInt = (1..6).random()
resultText.text = (resultText.text.toString().toInt() + randomInt).toString()
}
```
这样,每次点击按钮,就会生成一个随机数并将其加到 TextView 中原有的数字上,最终显示出和。