Search code examples
androidandroid-alertdialogandroid-textinputlayoutmaterial-componentsmaterial-components-android

How to add margin around a View in MaterialAlertDialogBuilder?


I need more information from users when they click on a particular item (from a list). I am displaying a dialog in order to get more info and I am using MaterialAlertDialogBuilder. This is how I am building it:

val v = LayoutInflater.from(context).inflate(R.layout.view_text_input, null)
MaterialAlertDialogBuilder(context, R.style.AlertDialogMaterialTheme)
                .setTitle(R.string.ofi_pleaseDescribe)
                .setView(v)
                .setPositiveButton(R.string.ok) { d, i ->
                    if (d == null) return@setPositiveButton
                    val txt = etInput.text?.trim()
                    etRationale.setText(txt)
                }
                .show()

This is its layout (view_text_input.xml).

<com.google.android.material.textfield.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/ofi_textInputLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginStart="16dp"
    android:layout_marginTop="24dp"
    android:layout_marginEnd="16dp"
    android:layout_marginBottom="8dp">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/etInput"
        style="@style/ofi_editText"
        android:hint="@string/ofi_title_hint" />

</com.google.android.material.textfield.TextInputLayout>

As you can see in the following screenshot, the above margins are getting ignored for some reason. Does anyone know why and how can I add margins around the view?

enter image description here


Solution

  • Use something different in your view.

    Something like:

    <FrameLayout
        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="wrap_content"
        android:paddingTop="?attr/dialogPreferredPadding"
        android:paddingStart="?attr/dialogPreferredPadding"
        android:paddingEnd="?attr/dialogPreferredPadding">
    
      <com.google.android.material.textfield.TextInputLayout
          android:id="@+id/text_input_layout"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          ...>
    
        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            .../>
      </com.google.android.material.textfield.TextInputLayout>
    
    </FrameLayout>
    

    Then:

    new MaterialAlertDialogBuilder(AlertDialogActivity.this)
                .setTitle(R.string.ofi_pleaseDescribe)
                .setView(R.layout.view_text_input)
                ...
                .show();
    

    enter image description here