0

so i want to use a custom dialog which contains an edittext; and the edittext has a textwatcher to convert the text inside of it. when i click the button for the first time and the dialog shows up, everything is fine but the second time the whole app crashes with this error : "The specified child already has a parent. You must call removeView() on the child's parent first ". i searched and tried almost everything but none of them worked. here is the code:


var dialogView = layoutInflater.inflate(R.layout.dialog, null, false)
var edittext = dialogView.findViewById<EditText>(R.id.alert_edittext)


findViewById<Button>(R.id.total_price_manual_input_button).setOnClickListener {
    //edittext=layoutInflater.inflate(R.layout.dialog, null, false).findViewById(R.id.alert_edittext)
    val builder = AlertDialog.Builder(this@MainActivity)
    builder.setView(dialogView)
        .create()
        .show()
}

}

i read on some topics that i have to create a new instance of the dialogview every time the dialog is being shown but when i tried to pass the "layoutInflater.inflate(R.layout.dialog, null, false)" directly to the setView(), the textwatcher did not get called.

also i tried to cast the dialogView parent as ViewGroup in order to cal removeView() on it but i got nullPointerException.

ADM
  • 20,406
  • 11
  • 52
  • 83
Emz
  • 9
  • 5
  • Move top 2 lines inside the On click . you are trying to use same view everytime thats why you getting this crash . Create View each time when you create dialog . – ADM Nov 19 '22 at 15:59
  • when i do that the addTextChangedListener does not get called. so the changes i want to make on the text wont be applied. – Emz Nov 19 '22 at 16:03
  • It will get called you need to move all that code inside the block where you create the Dialog .. Do not use any global variable with dialog view .. – ADM Nov 19 '22 at 16:07
  • Thank you a lot! this worked perfectly.moving the textchangedlistener to the block saved me. – Emz Nov 19 '22 at 16:28

0 Answers0