I'm creating a custom dialog, but when the user opens it for the second time, I get this exception: The specified child already has a parent. You must call removeView() on the child's parent first
I tried to call removeView on mDialog but I cannot. This error is common so I tried to implement solutions on other posts; when inflating mCustomDatePicker, I tried to set the root (in the constructor) as the parent of the inflated view, but it didn't help.
class SignupStageOne : AppCompatActivity() {
private var mCalendar : Calendar? = null
private var day: Int? = null
private var month: Int? = null
private var year: Int? = null
private var age: String? = null
private val firebaseDatabase = FirebaseDatabase.getInstance().reference
private val firebaseAuth = FirebaseAuth.getInstance()
val user = firebaseAuth.currentUser
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.example.meet.R.layout.activity_signup_stage_one)
val mCustomDatePicker = layoutInflater.inflate(com.example.meet.R.layout.custom_date_picker, datePickerLayout, false)
var mDatePicker = mCustomDatePicker.findViewById(com.example.meet.R.id.mDatePicker) as DatePicker
mDatePicker.maxDate = (Calendar.getInstance().getTime().getTime())
val mDialog = AlertDialog.Builder(this)
mDialog.setView(mCustomDatePicker)
mDialog.setPositiveButton("OK", object : DialogInterface.OnClickListener {
override fun onClick( dialog: DialogInterface, which: Int) {
}
}).setNegativeButton("Cancel", object: DialogInterface.OnClickListener {
@Override
override fun onClick( dialog: DialogInterface, which: Int) {
dialog.dismiss()
}
})
mDialog.create()
ageET.setOnFocusChangeListener{ view, hasFocus ->
if (hasFocus) {
mDialog.show()
}
}
}
I also tried to inflate the view like so:
layoutInflater.inflate(com.example.meet.R.layout.custom_date_picker, null, false)
But it didn't help.
My XML:
<RelativeLayout
android:id="@+id/datePickerLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<DatePicker
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/mDatePicker"
android:layout_gravity="center_horizontal"
android:spinnersShown="true"
android:calendarViewShown="false"
android:layout_alignParentTop="true"/>
</RelativeLayout>