アプリ名:get_time(適当)
<完成形>
・クリックしたら、2022/01/17 02:03:37(月)と表示される。
<おまけ>
一番下に、「エミュレータの時刻が合っていないときは?」を書いています。
<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/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:text="時刻を表示させる"
app:layout_constraintBottom_toTopOf="@+id/btn_1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="クリック"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<Kotolin>
package com.example.get_time
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//時刻を取得し、型を作る Eは曜日のこと
val date1 = LocalDateTime.now()
val date2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss(E)")
val date3 = date2.format(date1)
// tv_time 時刻を表示するテキストビュー
// btn_1 ボタン
val tv_time:TextView = findViewById(R.id.tv_time)
val btn_1:Button = findViewById(R.id.btn_1)
btn_1.setOnClickListener {
//例)2022/01/17 02:03:37(月)
tv_time.text = date3
}
}
}
エミュレータの時刻が合っていないときは?
エミュレターにて以下のとおりに設定します。