Search code examples
androidkotlinviewandroid-alertdialogandroid-viewbinding

MaterialAlertDialogBuilder crashes and shows error: The specified child already has a parent, when using custom view


when using custom layout with MaterialAlertDialog, it crashes and gives me this error:

    java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
        at com.example.applux.SettingsFragment.onViewCreated$lambda-3(SettingsFragment.kt:64) // line 64

SettingsFragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding = FragmentSettingsBinding.bind(view)

        binding.settingsClickUsername.setOnClickListener {
            val valueBinding = EditValuesBinding.inflate(layoutInflater)
            MaterialAlertDialogBuilder(requireContext())
                .setTitle("Edit your username")
                .setView(valueBinding.editValue)
                .setPositiveButton("Save"){ dialog, p ->

                }
                .setNegativeButton("Cancel"){ dialog, p ->

                }
                .show() // this is the line 64
        }
}

edit_values.xml layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edit_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Any solution to this error, and why it happens?


Solution

  • I found the solution, i must pass valueBinding.root to setView() instead of valueBinding.editValue, because TextInputEditText is attached to the ConstraintLayout, thanks to Mike M for helping.