3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Kotlin】タイマーを使ってみて詰まった所【AndroidStudio】

Last updated at Posted at 2019-07-13

少し詰まった所があったのでメモしときます。
・タイマー処理内でビューを更新する場合ハンドラー使わないとダメっぽい。

ビルドは通るけどすぐ落ちる
logは出せるみたいビュー更新はNG

MainActivity.kt
package com.example.wifiautoswitching

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.TextView
import java.util.*
import kotlin.concurrent.schedule

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        val messageView: TextView = findViewById(R.id.textView)
        //val mHandler = Handler()
        var x = 0

        var timerCallback1: TimerTask.() -> Unit = {

            var str = Integer.toString(x)
            //mHandler.post{messageView.text = str}
            messageView.text = str
            System.out.println(str)
            x++
            //this.cancel()
        }
        Timer().schedule(0, 1000, timerCallback1)

    }
}

これでビュー更新ができる

MainActivity.kt
package com.example.wifiautoswitching

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.TextView
import java.util.*
import kotlin.concurrent.schedule

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        val messageView: TextView = findViewById(R.id.textView)
        val mHandler = Handler()
        var x = 0

        var timerCallback1: TimerTask.() -> Unit = {

            var str = Integer.toString(x)
            mHandler.post{messageView.text = str}
            //messageView.text = str
            System.out.println(str)
            x++
            //this.cancel()
        }
        Timer().schedule(0, 1000, timerCallback1)

    }
}

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?