Search code examples
androidandroid-layoutandroid-linearlayoutandroid-xml

How to properly layout an edit text horizontally in android?


I am trying to figure how I can properly layout an edit text in between two views so that It will take up the whole width nicely in all screen sizes.

Here is my xml:

<LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp">
                <ImageView
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_marginLeft="5dp"
                    android:src="@drawable/country_india"/>
                <EditText
                    android:layout_width="250dp"
                    android:layout_height="wrap_content"
                    android:hint="Leave a comment"
                    android:layout_gravity="bottom"/>
                <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/icon_pencil_2_small"
                    android:background="@color/white"
                    android:layout_gravity="bottom"
                    android:layout_marginBottom="5dp"/>
            </LinearLayout>

Here is what it looks like: enter image description here

Hope you guys can help!


Solution

  • you should be using android:layout_weight="1" instead of fixing the width if you'd like to fit the EditText to fit in.

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:orientation="horizontal">
    
        <ImageView
            android:layout_height="50dp"
            android:layout_marginLeft="5dp"
            android:layout_width="50dp"
            android:src="@drawable/country_india"/>
    
        <EditText
            android:hint="Leave a comment"
            android:layout_gravity="bottom"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_width="0dp"/>
    
        <ImageButton
            android:background="@color/white"
            android:layout_gravity="bottom"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:layout_width="wrap_content"
            android:src="@drawable/icon_pencil_2_small"/>
    </LinearLayout>