单击Kotlin中的肯定按钮后,停止关闭AlertDialog

问题描述

标题说我需要的东西

我需要在单击肯定按钮后关闭AlertDialog,因为当用户单击肯定按钮时,我需要在该AlertDialog中显示一条消息

a找到了这个Stop AlertDialog from closing on positive button click,但我不能在Kotlin中使用它

  alertDialog.setPositiveButton("ok"){ dialogInterface,i ->
        if(myET.text.toString().length !in 10..100){
            myET.error = "text size not in the range"
            //here must not close
        }else{
            myfunction()
            // only here must close
        }
  }

解决方法

使用具有自定义视图的AlertDilaog。

val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(this)
    val inflater = this.layoutInflater
    val dialogView: View = inflater.inflate(R.layout.custom_dialog_layout,null)
    dialogBuilder.setView(dialogView)

    val positiveButton =
        dialogView.findViewById<Button>(R.id.positive_button) as EditText

    val alertDialog: AlertDialog = dialogBuilder.create()
    alertDialog.show()
    
    positiveButton.setOnClickListener { 
        //do whatever you have to do here

        //dismiss dialog when done
        alertDialog.dismiss()
}
,

尝试以下代码,希望它能起作用

 final AlertDialog dialog = new AlertDialog.Builder(context)
    .setView(v)
    .setTitle(R.string.my_title)
    .setPositiveButton(android.R.string.ok,null) 
    .setNegativeButton(android.R.string.cancel,null)
    .create();

 dialog.setOnShowListener(new DialogInterface.OnShowListener() {

@Override
public void onShow(DialogInterface dialogInterface) {

    Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // TODO Do something

            //Dismiss once everything is OK.
            dialog.dismiss();
        }
    });
}
});
dialog.show();