LoginSignup
0
0

Android スレッド内でUIの表示を変更する

Last updated at Posted at 2023-06-11
package com.a.thread

import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.concurrent.atomic.AtomicInteger

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val handler = Handler(mainLooper)

        val myRunnable = object : Runnable {
            var count: AtomicInteger = AtomicInteger(0)

            override fun run() {
                handler.postDelayed(this, 1000)

                count.incrementAndGet()

                Log.d("count", "" + count)

                val textView = findViewById<TextView>(R.id.text_view)
                textView.text = count.toString()
            }
        }

        val startBtn = findViewById<Button>(R.id.button_start)
        val interruptBtn = findViewById<Button>(R.id.button_interrupt)

        startBtn.setOnClickListener {
            handler.post(myRunnable)
        }

        interruptBtn.setOnClickListener {
            handler.removeCallbacks(myRunnable)
        }
    }
}

0
0
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
0
0