表題の通り、ランダムに0.5秒ごとに切り替わる数値(以下A)と、ある一定の数値(B)の計算をする機能を実装したいです。
その計算結果もAと同様に0.5秒ごとに切り替わるように表示させたいです。
まずAは、0.5秒ごとに100以下の数値がランダムに切り替わって表示されます。
以下、コード
MainActivity.kt
kotlin
1 2override fun onCreate(savedInstanceState: Bundle?) { 3 super.onCreate(savedInstanceState) 4 setContentView(R.layout.activity_main) 5 6//100以下の数値を0.5秒ごとにランダム表示(スタートボタンで開始) 7 buttonSTART.setOnClickListener { 8 GlobalScope.launch { 9 while (true){ 10 delay1(500L) 11 textView.text = "${(1..100).random()}" 12 } 13 } 14 }
ランダムに表示するビュー
activity_main.xml
kotlin
1 <TextView 2 android:layout_width="0dp" 3 android:layout_height="0dp" 4 android:id="@+id/textViewNumberA" 5 android:textAlignment="center" 6 android:background="@android:color/darker_gray" 7 android:textSize="36sp" 8 app:layout_constraintTop_toBottomOf="@+id/buttonMOVE" 9 app:layout_constraintEnd_toStartOf="@+id/buttonEMG" 10 android:layout_marginBottom="17dp" 11 app:layout_constraintStart_toStartOf="parent" 12 android:layout_marginStart="25dp" 13 app:layout_constraintBottom_toBottomOf="parent" 14 android:layout_marginEnd="21dp" 15 />
一定の値Bを入力するのEditText
kotlin
1 2 <EditText 3 android:layout_width="0dp" 4 android:layout_height="0dp" 5 android:inputType="number" 6 android:ems="10" 7 android:id="@+id/editNumberB" 8 android:background="@android:color/darker_gray" 9 android:autofillHints="" tools:ignore="LabelFor" 10 app:layout_constraintTop_toBottomOf="@+id/visualizer" app:layout_constraintEnd_toStartOf="@+id/mvc" 11 app:layout_constraintBottom_toTopOf="@+id/buttonMOVE" app:layout_constraintStart_toStartOf="parent" 12 android:layout_marginStart="21dp" android:layout_marginEnd="15dp" 13 /> 14 15
Webで計算アプリの作り方などを参照して書いてみたのですが、もちろんうまくいかず、
ガバガバなコードになっていると思います。
流れとしては、
1.Bを入力
2.スタートボタンを押すと、Aが0.5秒ごとに表示(View1)、と同時に計算結果も表示(View2)
になります。
以下、書いてみたコード(本当にぐちゃぐちゃなコードです)
kotlin
1 2//計算 3 buttonSTART.setOnClickListener { 4 5 //数値Bの入力を取得 6 val get_b = findViewById<EditText>(R.id.editNumberB) 7 val st_b = editNumberB.text.toString() 8 9 //数値Aを取得 10 val get_a = findViewById<TextView>(R.id.textViewNumberA) 11 val st_a = textViewNumberA.text.toString() 12 13 val a = Integer.parseInt(st_a) 14 val b = Integer.parseInt(st_b) 15 16 //計算 17 val kekka = b / a * 100 18 19 //表示 20 val set_kekka = findViewById<TextViewKekka>(R.id.mvc) 21 }
エミュレーターでランさせたところ、STARTボタンをおしたところでアプリが落ちます。
アドバイスよろしくお願いいたします。