DialogFragment

Kotlin

18時から朝の6時までは営業時間外ですと表示する

通常のAlertDialog.BuilderはEditTextなどを含みませんが、それらを含みたいときはDialogFragmentを使います

res/layout/dialog_off_hours.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"
    android:id="@+id/dialogRoot"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#CC000000">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="16dp"
        app:cardCornerRadius="16dp"
        app:cardElevation="8dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.9">

        <TextView
            android:id="@+id/tvOffHoursMessage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="申し訳ございませんが、営業時間外です"
            android:textSize="20sp"
            android:textColor="#000000"
            android:gravity="center"
            android:padding="24dp"/>
    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

OffHoursDialogFragment.kt

class OffHoursDialogFragment : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireContext(), android.R.style.Theme_Black_NoTitleBar_Fullscreen)
        dialog.setContentView(R.layout.dialog_off_hours)
        dialog.setCancelable(false) // バックキーでも閉じられない
        return dialog
    }
}

HomeActivity.kt

override fun onResume() {
    super.onResume()
    checkBusinessHours()
}

private fun checkBusinessHours() {
    val calendar = Calendar.getInstance()
    val hour = calendar.get(Calendar.HOUR_OF_DAY)

    if (hour < 6 || hour >= 18) {
        val dialog = OffHoursDialogFragment()
        dialog.show(supportFragmentManager, "OffHoursDialog")
    }
}
BACK