Android 9 Development Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

How it works...

When using vertical orientation with LinearLayout, the child Views are created in a single column (stacked on top of each other). The first two Views use the android:layout_height="wrap_content" attribute, giving them a single line each. To specify the height, editTextMessage uses the following:

android:layout_height="0dp" 
android:layout_weight="1" 

When using LinearLayout, it tells Android to calculate the height based on the weight. A weight of 0 (the default if not specified) indicates the View should not expand. In this example, editTextMessage is the only View defined with a weight, so it alone will expand to fill any remaining space in the parent layout.

When using the horizontal orientation, specify android:layout_height="0dp" (along with the weight) to have Android calculate the width.

It might be helpful to think of the weight attribute as a percentage. In this case, the total weight defined is 1, so this View gets 100 percent of the remaining space. If we assigned a weight of 1 to another View, the total would be 2, so this View would get 50 percent of the space. Try adding a weight to one of the other Views (make sure to change the height to 0dp as well) to see it in action.

If you added a weight to one (or both) of the other Views, did you notice the text position? Without specifying a value for gravity, the text just remains in the center of the View space. The editTextMessage View specifies android:gravity="top", which forces the text to the top of the View.