Ayush
Ayush

Reputation: 23

custom calendar dialog in android project

In my project, I add a custom layout for the dialog to show the time picker to the user.

it works fine but sometimes when the dialog opens it blinks and when I set the time and click on the cancel or ok it first resets the time and then on the second click it dismisses the dialog.

below is the function I am calling from my fragment.

fun selectTime(context: Context) {

val currentTime = Calendar.getInstance()
val hour = currentTime.get(Calendar.HOUR_OF_DAY)
val minute = currentTime.get(Calendar.MINUTE)

val dialog = Dialog(context)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCancelable(false)
dialog.setContentView(R.layout.custom_time_picker)
Log.e("time-->","first")
val timePicker=dialog.findViewById<TimePicker>(R.id.timePicker)
val ok = dialog.findViewById<TextView>(R.id.ok)
val cancel = dialog.findViewById<TextView>(R.id.cancel)
Log.e("time-->","second")
timePicker.setIs24HourView(true)
timePicker.hour = hour
timePicker.minute = minute

Log.e("time-->","third")
cancel.setOnClickListener {

  //  dialog.cancel()
    dialog.dismiss()
}

ok.setOnClickListener {
    val selectedHour = timePicker.hour
    val selectedMinute = timePicker.minute
    // Do something with the selected time
    Log.e("time-->","$selectedHour:$selectedMinute")
    dialog.dismiss()
}

dialog.show()
dialog.window?.setBackgroundDrawableResource(R.color.transparent)
val window = dialog.window
window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)

I want to dismiss the dialog on the d=first click on cancel or ok also the log are printing two times on click don't know why

Upvotes: 0

Views: 55

Answers (1)

Ayush
Ayush

Reputation: 23

I got the answer myself It working by adding the below line of code

 var dialogInstance: Dialog? = null
    fun selectTime(context: Context, onTimeSelected: (String) -> Unit) {
        val dialog: Dialog
        if (dialogInstance != null && dialogInstance!!.isShowing) {
            return
        } else {
            dialog = Dialog(context)
            dialogInstance = dialog
        }

// rest of code here

Upvotes: 0

Related Questions