現在Kotlin勉強中のものです。
非同期処理について勉強しています。
参考にしているのはYouTubeの
Androidアプリ開発研修【21新卒技術研修】
https://youtu.be/91XQebVNnbI
という動画です。(2:26:28~始まる実習5-2のところです)
この中のKotlinCoroutinesについて実践して見ているのですがなぜか同じように書いてもエラーが出てしまいます。
まだ構造を理解しきれていません><
詳しい方、下記コードを訂正していただけませんか?教えていただきたいです><
現状エラーが出ている箇所には⭐️マークをつけています。
よろしくお願いいたします!
MainActivity.ktの内容
MainActivity.kt
package com.example.kotlin_coroutines import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val startButton = findViewById<Button>(R.id.startButton) // ボタンを連打したときに何度も処理してしまうのを防ぐため。jobを設定する ⭐️val job: Job? = null // エラー内容⇨Unresolved reference: Job startButton.setOnClickListener{ // 下記にすることで連打したときに何度も処理されることを防げる。coroutinesが複数起動しなくなるということ。 if (job?.isActive == true) return@setOnClickListener job = ⭐️lifecycleScope.launch { // エラー内容⇨Unresolved reference: lifecycleScope val textView = findViewById<TextView>(R.id.textView) var count = 0 try { while (true) { textView.text = "${count}秒" count++ ⭐️delay(1000) // エラー内容⇨Suspend function 'delay' should be called only from a coroutine or another suspend function } } finally { textView.text = "停止" } } } val stopButton = findViewById<Button>(R.id.stopButton) stopButton.setOnClickListener { job?.cancel() } } }
activity_main.xmlファイルの内容
activity_main.xml
<?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="TextView" android:textSize="26sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/startButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="178dp" android:text="開始" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" /> <Button android:id="@+id/stopButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="178dp" android:text="停止" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
まだ回答がついていません
会員登録して回答してみよう