Search code examples
androiddrawingandroid-relativelayoutfill-parent

How to draw elements from the right to the left?


I want to have a button at the rigth of the screen, and an edittext which take all the place it can take at the left of the button. How can I do?

This xml print me the button at the left of the screen but nothing before :/

<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
>

    <Button 
        android:id="@+id/index_bouton_recherche"
        android:layout_width="45px"
        android:layout_height="45px"
        android:background="@drawable/loupe"
    />

    <EditText 
        android:id="@+id/index_champs_recherche"
        android:layout_width ="fill_parent"
        android:layout_height="wrap_content"
        android:maxLines="1" 
        android:layout_toLeftOf="@id/index_bouton_recherche"
    />

Solution

  • When I have to do this, I use LinearLayout and layout_weight xml attribute. This XML would solve your problem:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
    >
        <EditText 
            android:id="@+id/index_champs_recherche"
            android:layout_width ="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:maxLines="1" 
        />
        <Button 
            android:id="@+id/index_bouton_recherche"
            android:layout_width="45px"
            android:layout_height="45px"
            android:background="@drawable/loupe"
        />
    </LinearLayout>
    

    The layout_width="0dp" means that initially, the view won't require any space. The Button is wrap_content, so it only require its space. The layout_weight attribute is applied after, and it shares the remaining space on the layout (the width for orientation=horizontal, height for vertical). Default view weight is 0, so with 1, the EditText will take 100% of the remaining space.