Search code examples
androidandroid-layoutandroid-activity

How to align two views in Android?


I have two views within Linear layout. One view is TextView and another one is EditText. I want aligned both of them. Here is the screenshot and code.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:background="#ccc"
    android:orientation="horizontal"
    android:layout_weight="1">

    <TextView
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:text="S1"
        android:background="#110faa">

    </TextView>

    <EditText
        android:layout_width="80dp"
        android:layout_height="20dp"
        android:background="#102df2"
        android:inputType="numberDecimal"
        android:importantForAutofill="no">

    </EditText>

</LinearLayout>

This is what it looks right now i don't want that top spacing on S1 text view.

Here is the screenshot:


Solution

  • Use android:layout_weight to divided width of LinearLayout and android:baselineAligned="false" for top spacing

     <LinearLayout android:layout_width="match_parent"
            android:layout_height="80dp"
            android:background="#ccc"
            android:orientation="horizontal"
            android:layout_weight="5"
            android:baselineAligned="false">
        
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="20dp"
                android:layout_weight="1"
                android:background="#110faa"
                android:text="S1">
        
            </TextView>
        
            <EditText
                android:layout_width="wrap_content"
                android:layout_height="20dp"
                android:layout_weight="4"
                android:background="#102df2"
                android:importantForAutofill="no"
                android:inputType="numberDecimal"></EditText>
        
        </LinearLayout>