Consider this layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="@+id/red"
android:background="@color/Red"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Red" />
</LinearLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
The TextView
is stretched horizontally all the way to the edges of the screen, but the height is limited by the string "Red" and is positioned at the top of the screen. Why is that so? Why is the TextView
stretched in only one dimension?
When I switch the orientation of the LinearLayout
s the effect is reversed: The TextView
is stretched from top to bottom, but its width is limited by the string "Red" and is aligned to the left of the screen.
That's how the Android weight
distribution is supposed to work. If a view
has weight in a LinearLayout
with horizontal orientation
, then it will acquire importance/weight in horizontal direction only. Similar is the case with LinearLayout
withvertical orientation
, the view gains importance/weight in the vertical direction. That's how the android weight
distribution works.
Note: Use width
(in case of horizontal orientation) or height
(in case of vertical orientation) as 0dp
instead of 'wrap_content' for better performance.