Home > Mobile >  AlertDialog custom view with setView() inflated
AlertDialog custom view with setView() inflated

Time:03-12

The layout:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_margin="16dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:text="test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <View
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <EditText
        android:text="08:00"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

and the code:

    AlertDialog.Builder(requireActivity()).apply {
        setTitle(R.string.settings)
        setView(R.layout.settings_dialog)
        setPositiveButton(R.string.save) { dialog, id ->

        }
        setNegativeButton(android.R.string.cancel, null)
    }.create()

and this is what it looks like:

enter image description here

The margin of the LinearLayout seems to have no effect. And the custom view seems to be inflated to the size of the screen, save for a margin that I think comes from the AlertDialog itself.

What is it that makes the custom view inflate this much? How to prevent it?

CodePudding user response:

You used weight on your View object and not on the other objects in this layout therefore this code will give 'View' the maximum place it can take and will leave your edittext and textview no place.

You can either add weight to the text and edittext by changing width to :

android:layout_width="0dp"

and adding this line:

android:layout_weight="1"

or you can remove the weight from the 'View' object.

CodePudding user response:

With this it looks ok:

LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="16dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:text="test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <EditText
        android:text="08:00"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Using padding instead of margin in the LinearLayout, and the height of the View set to "0dp" instead of "wrap_content".

  • Related