1

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?

Abdelillah
  • 79
  • 1
  • 14
  • 1
    `setView(valueBinding.editValue)` – Change that to `setView(valueBinding.root)` instead. As you have it now, you're telling the builder to add just the `TextInputEditText` to the `Dialog`'s content, but the `TextInputEditText` is already attached to the `ConstraintLayout`, which is really what you meant to pass there instead. – Mike M. Dec 05 '21 at 16:47

1 Answers1

2

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.

Abdelillah
  • 79
  • 1
  • 14