Monday, December 15, 2014

Align LinearLayout view content been shifted down in android

The weight system of LinearLayout makes using it to build rows with even spacing across the children simple and effective. However, as often as you may have done this, you might have also run into a perplexing issue that arises when the text of one or more elements inside the row gets long enough to force line wrapping.

Not only has the view content been shifted down, but the parent container isn’t sized to fit the larger height this creates, so part of the shifted view is clipped! Also notice that the view is shifted even in cases where the multiple lines don’t make the view inherently taller. This behavior makes absolutely no sense, until you understand what is actually going on under the hood. If we take a much closer look at the alignment of the child elements, something interesting emerges.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_baselineAligned="false"
    android:orientation="horizontal">
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="12dp"
        android:text="Last" />
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="12dp"
        android:text="Next" />
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="12dp"
        android:text="Reload Content" />
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="12dp"
        android:text="Exit" />
</LinearLayout>

No comments:

Post a Comment