Home > Net >  java.lang.IllegalStateException: The specified child already has a parent. You must call removeView(
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView(

Time:11-23

I have a method that is displaying a custom Dialog Box

fun showDialog(){

val resultsDialog = Dialog(this)

resultsDialog.setContentView(dialogBinding.root)
dialogBinding.tvDialogCategory.text = CategoryType.HISTORY.name

dialogBinding.tvDialogSetMeetMinimumCriteria.text =displayResultString

resultsDialog.create()

resultsDialog.show()
}

However, when I call this method again after making some validations in my Activity code,

myButton.setOnClickListener{
  //some validation code here
  showDialog()
 

}

I'm getting the error: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first

I've tried various ways to solve this issue but not able to do so. How can I solve this issue? Thanks.

CodePudding user response:

Put result dialog into global variable

class YourActivity : BaseActivity(){  
  lateinit var resultsDialog

Then Breakdown your show dialog into 2 method, one for initialize the dialog, the other for showing the dialog

fun initDialog(){
  resultsDialog = Dialog(this)
  resultsDialog.setContentView(dialogBinding.root)
  dialogBinding.tvDialogCategory.text = CategoryType.HISTORY.name
  dialogBinding.tvDialogSetMeetMinimumCriteria.text =displayResultString
  resultsDialog.create()
}

fun showDialog(){
  resultsDialog.show()
}

after that, call initDialog() only once on your oncreate method and call your showDialog() on myButton clicklistener

  • Related