LoginSignup
0
0

More than 3 years have passed since last update.

【Kotlin 初心者】DataPikerで日時表示する

Posted at

イメージ

Kotlinで簡単にiPhoneみたいな表示で日時を表示することができます

実装

コードはいけてないとこありますが、ご容赦を、、、

MainActivity.kt

package com.example.datapicker

import android.app.AlertDialog
import android.app.DatePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

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

        val dataPiker = findViewById<TextView>(R.id.date_picker)
        dataPiker.setOnClickListener {
            showDataPicker()
        }

    }

    private fun showDataPicker() {

        val dataPiker = findViewById<TextView>(R.id.date_picker)
        val datePickerDialog = DatePickerDialog(this,
                AlertDialog.THEME_HOLO_DARK,
                DatePickerDialog.OnDateSetListener() { view, year, month, dayOfMonth->
                    dataPiker.text = "${year}/${month + 1}/${dayOfMonth}"
                }, 2020, 12, 1)
        datePickerDialog.show()
    }
}
ActivityMain.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/date_picker"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="ここをタップして"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

終わりに

Githubにもあげているので困っている方いたらぜひ!
https://github.com/naoyukitsuruo/dataPickerSample

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