import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.TextView import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val randomNumber = (0..2).random() } fun showMessage(view: View) { if (view.id == random || view.id == random ){ // Toast.makeText(this, "正解!", Toast.LENGTH_LONG).show() }else if (view.id == random + 1) { //はずれ Toast.makeText(this, "はずれ!正解は1", Toast.LENGTH_LONG).show() }else if (view.id == random + 2){ //はずれ Toast.makeText(this, "はずれ!正解は3", Toast.LENGTH_LONG).show() } } } レイアウトのコードです <?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"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1から3のどれかを押す" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="showMessage" android:text="2" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="showMessage" android:text="1" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@+id/button" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="showMessage" android:text="3" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/button" app:layout_constraintTop_toBottomOf="@+id/textView" /> ### ヘディングのテキスト 1、2、3のボタンを押したときにランダムで正解かハズレを表示させたいです。 randomNumberの使い方と表示の仕方がわかりません。
回答1件
あなたの回答
tips
プレビュー