ボタンを押して日時をテキストビューに表示する単純なもの
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" android:id="@+id/textView_01"/>
<Button
android:text="@string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_01" android:layout_marginTop="29dp"
app:layout_constraintTop_toBottomOf="@+id/textView_01" app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="167dp" android:layout_marginStart="167dp" android:layout_marginBottom="279dp"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="156dp" android:layout_marginRight="156dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.example.datepicker
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textButton: Button = findViewById(R.id.button_01)
val messageView: TextView = findViewById(R.id.textView_01)
textButton.setOnClickListener {
val df = SimpleDateFormat("yyyy年MM月dd日 HH:mm")
val dateNow = df.format(Date())
messageView.text = dateNow
}
}
}
