MaterialAlertDialogBu​​ilder在自定义视图editText

时间:2019-11-20 14:45:17

标签: android android-edittext illegalstateexception material-dialog

当尝试读取editText内容时,AlertDialog(Material)崩溃。

AlertDialog:

MaterialAlertDialogBuilder(activity)
            .setTitle(title)
            .setMessage(message)
            .setView(R.layout.dialog_settings_entry)
            .setPositiveButton(getString(R.string.text_change)) { dialog, which ->
                etUserInput.hint = message
                sgr = etUserInput.text.toString() // << crashes here
                dialog.dismiss()
            }
            .setNegativeButton(getString(android.R.string.cancel)) { dialog, _ ->
                dialog.dismiss()
            }
            .show()

单击肯定按钮时,结果如下:

    java.lang.IllegalStateException: etUserInput must not be null
        at com.home.profile.SettingsFragment$buildAlertDialog$1.onClick(SettingsFragment.kt:332)
        at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)

etUserInput 是位于单独布局中的简单editText。 不确定崩溃原因。希望对它有任何见识或任何有用的材料示例。

1 个答案:

答案 0 :(得分:4)

DialogInterface投射到AlertDialog,然后使用findViewById

科特琳:

val et = (dialog as? AlertDialog)?.findViewById<EditText>(R.id.etUserInput)
val text = et?.text.toString()

-

Java:

EditText et = ((AlertDialog)dialog).findViewById(R.id.etUserInput);
String text = et.getText().toString();

-

MaterialAlertDialogBuilder(activity)
            .setTitle(title)
            .setMessage(message)
            .setView(R.layout.dialog_settings_entry)
            .setPositiveButton(getString(R.string.text_change)) { dialog, which ->
                val text = (dialog as? AlertDialog)?.findViewById<EditText>(R.id.etUserInput)?.text?.toString()

                dialog.dismiss()
            }
            .setNegativeButton(getString(android.R.string.cancel)) { dialog, _ ->
                dialog.dismiss()
            }
            .show()