目的
OKを押したときだけでなく、キャンセル(Cancel)を押したときにも処理をしたい
環境
- Kotlin 1.3.21
- Android 8.0 (Oreo)
- AndroidStudio 3.3.2
動作イメージ
Buttonを押したらDialogFragmentを表示します。
DialogFragmentでOKを押したら入力日付をButtonのテキストに表示し、キャンセル(Cancel)を押したらButtonのテキストに"指定なし"を表示します。
実装
layoutファイル
シンプルにButtonだけの画面にします。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<Button
android:text="指定なし"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/date_button"
android:layout_marginTop="16dp" app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"/>
</android.support.constraint.ConstraintLayout>
activityファイル
DialogFragmentのonCancelに処理したい内容を書くだけです。
OKを押したときの処理については、こちらの記事に書いています。
MainActivity.kt
package com.example.kanehiro.datetest
import android.app.DatePickerDialog
import android.app.Dialog
import android.content.DialogInterface
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.widget.Button
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mDate = findViewById<Button>(R.id.date_button)
/* 日付を入力する時に使用するinnerクラス
DialogFragmentで日付を入力できるカレンダーを表示する */
class DateDialogFragment() : DialogFragment() {
/* DatePickerDialogを返却する関数
この関数で、日付を選択した後の処理や、選択できる日付範囲、Dialogのタイトルを設定する */
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// 省略
}
/* DialogFragmentでキャンセルを押した際の処理 */
override fun onCancel(dialog: DialogInterface?) {
super.onCancel(dialog)
// ここにキャンセルを押したときにしてほしい処理を書く
mDate.text = "指定なし"
}
}
/* 日付を指定するボタンを押したとき */
mDate.setOnClickListener {
// DialogFragmentを生成し、表示
DateDialogFragment().show(supportFragmentManager, mDate::class.java.simpleName)
}
}
}