LoginSignup
0
0

Android Studio: デジタルクロック

Last updated at Posted at 2023-10-27

image.png

画面

res/layout/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="Hello World!"
        android:textSize="40sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

プログラム

MainActivity.kt
package com.example.clock01

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {
    private val handler = Handler(Looper.getMainLooper())
    private lateinit var textView: TextView

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

        val delayMillis: Long = 1 * 1000

        handler.postDelayed(object : Runnable {
            override fun run() {
                fetchApi()
                handler.postDelayed(this, delayMillis)
            }
        }, delayMillis)
    }

    private fun fetchApi() {
        val textView = findViewById<TextView>(R.id.textView)
        println("*** fetchAPI *** aaa ***")

        thread {
            try {
                println("*** fetchAPI *** ccc ***")

                val now = LocalDateTime.now()
                val df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                val fdate = df.format(now)
                println(fdate.toString())

                Handler(Looper.getMainLooper()).post {

                    textView.text = fdate
                }
            } catch (e: Exception) {
                Log.d("response-fetchApi", "debug $e")
            }
        }
    }

}

注意

Build には、
minSDK 26 以上にする必要があります。

Android 8.1.0 以上で動作します。

0
0
1

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