androidxmlkotlinandroid-dialogfragment

DialogFragment custom view no background


I'm trying to inflate a custom view in a DialogFragment but the container view's are not showing up. Note I haven't found any post that matches this exactly, so if there is, please share, TIA. here is my XML (very simple)

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:background="@drawable/billnotifselectiondialog"
        android:layout_marginHorizontal="45dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

        <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:background="@color/secondary_200"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

My Class:

class BillNotifSelectionDialog:  DialogFragment() {
    private lateinit var binding: TestDialogLayoutBinding
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View = TestDialogLayoutBinding.inflate(LayoutInflater.from(context),container, false).apply {
        binding = this
    }.root
}

I'm invoking the class in my fragment with

BillNotifSelectionDialog().show(parentFragmentManager, "tag")

Here is the result, I can only see the button, not the ConstraintLayout:

enter image description here


Solution

  • This is a common issue of using ConstraintLayout as the root layout of DialogFragments.

    One fix is to Replace it with RelativeLayout; but it's not recommended as per documentation quote:

    For better performance and tooling support, you should instead build your layout with ConstraintLayout.

    Instead of that you'd fix it programmatically by designating the dialog layout to match the parent with dialog.window.setLayout:

    class BillNotifSelectionDialog : DialogFragment() {
       //..... rest of code omitted
    
        override fun onStart() {
            super.onStart()
            dialog!!.window!!.setLayout(MATCH_PARENT, MATCH_PARENT)
        }
    
    }