現在Kotlin勉強中のものです。
非同期処理について勉強しています。
参考にしているのはYouTubeの
Androidアプリ開発研修【21新卒技術研修】
https://youtu.be/91XQebVNnbI
という動画です。(2:26:28~始まる実習5-2のところです)
この中のKotlinCoroutinesについて実践して見ているのですがなぜか同じように書いてもエラーが出てしまいます。
まだ構造を理解しきれていません><
詳しい方、下記コードを訂正していただけませんか?教えていただきたいです><
現状エラーが出ている箇所には⭐️マークをつけています。
よろしくお願いいたします!
MainActivity.ktの内容
MainActivity.kt
1package com.example.kotlin_coroutines 2 3import androidx.appcompat.app.AppCompatActivity 4import android.os.Bundle 5import android.widget.Button 6import android.widget.TextView 7 8class MainActivity : AppCompatActivity() { 9 override fun onCreate(savedInstanceState: Bundle?) { 10 super.onCreate(savedInstanceState) 11 setContentView(R.layout.activity_main) 12 13 val startButton = findViewById<Button>(R.id.startButton) 14// ボタンを連打したときに何度も処理してしまうのを防ぐため。jobを設定する 15 ⭐️val job: Job? = null 16// エラー内容⇨Unresolved reference: Job 17 startButton.setOnClickListener{ 18// 下記にすることで連打したときに何度も処理されることを防げる。coroutinesが複数起動しなくなるということ。 19 if (job?.isActive == true) return@setOnClickListener 20 job = ⭐️lifecycleScope.launch { 21// エラー内容⇨Unresolved reference: lifecycleScope 22 val textView = findViewById<TextView>(R.id.textView) 23 var count = 0 24 try { 25 while (true) { 26 textView.text = "${count}秒" 27 count++ 28 ⭐️delay(1000) 29// エラー内容⇨Suspend function 'delay' should be called only from a coroutine or another suspend function 30 31 } 32 } finally { 33 textView.text = "停止" 34 } 35 } 36 } 37 val stopButton = findViewById<Button>(R.id.stopButton) 38 stopButton.setOnClickListener { 39 job?.cancel() 40 } 41 } 42}
activity_main.xmlファイルの内容
activity_main.xml
1<?xml version="1.0" encoding="utf-8"?> 2<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".MainActivity"> 8 9 10 <TextView 11 android:id="@+id/textView" 12 android:layout_width="wrap_content" 13 android:layout_height="wrap_content" 14 android:text="TextView" 15 android:textSize="26sp" 16 app:layout_constraintBottom_toBottomOf="parent" 17 app:layout_constraintEnd_toEndOf="parent" 18 app:layout_constraintStart_toStartOf="parent" 19 app:layout_constraintTop_toTopOf="parent" /> 20 21 <Button 22 android:id="@+id/startButton" 23 android:layout_width="wrap_content" 24 android:layout_height="wrap_content" 25 android:layout_marginBottom="178dp" 26 android:text="開始" 27 app:layout_constraintBottom_toBottomOf="parent" 28 app:layout_constraintStart_toStartOf="parent" /> 29 30 <Button 31 android:id="@+id/stopButton" 32 android:layout_width="wrap_content" 33 android:layout_height="wrap_content" 34 android:layout_marginBottom="178dp" 35 android:text="停止" 36 app:layout_constraintBottom_toBottomOf="parent" 37 app:layout_constraintEnd_toEndOf="parent" /> 38</androidx.constraintlayout.widget.ConstraintLayout>
回答1件
あなたの回答
tips
プレビュー