How to prevent a dialog from closing when a button is clicked

后端 未结 18 2160
无人及你
无人及你 2020-11-21 23:59

I have a dialog with EditText for input. When I click the \"yes\" button on dialog, it will validate the input and then close the dialog. However, if the input

18条回答
  •  野性不改
    2020-11-22 00:40

    Kotlin

    val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_userinput, null)
            val dialogBuilder = MaterialAlertDialogBuilder(requireContext(), R.style.AlertDialogTheme)
       
            dialogBuilder.setView(dialogView)
            dialogBuilder.setCancelable(false)
            dialogBuilder.setPositiveButton("send",null)
            dialogBuilder.setNegativeButton("cancel") { dialog,_ ->
            dialog.dismiss()
            }
    
    
            val alertDialog = dialogBuilder.create()
            alertDialog.show()
    
            val positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
            positiveButton.setOnClickListener {
                val myInputText = dialogView.etxt_userinput.text.toString().trim()
                if(myInputText.isNotEmpty()){
                 //Do something
                }else{
                    //Prompt error
                    dialogView.etxt_userinput.error = "Please fill this"
                }
            }
    

    We just create an AlertDialog with the dialogBuilder and then just set the positive button as we want

提交回复
热议问题