The ultimate research on Layout_weight in Android, androidlayout

Source: Internet
Author: User

The ultimate research on Layout_weight in Android, androidlayout

In the past, Layout_weight attributes were often used in UI layout, and sometimes some layout problems were puzzling. I always wanted to do in-depth analysis, but I was always impatient. If you encounter problems, find an alternative solution, but it will not last long. This time I made up my mind to reveal it!

I have never understood what Layout_weight meant before. I wrote code and tested it myself. I recently read a post and thought it was a good analysis,Paste it to learn.


The layout file is:
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "horizontal"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<Button
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: layout_weight = "1"
Android: text = "Button1"
/>
<Button
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: layout_weight = "2"
Android: text = "Button2"
/>
</LinearLayout>
The layout is as follows: button1 accounts for 2/3, while button2 accounts for 1/3.


However, if you change the property android: layout_width = "fill_parent" of the button in the layout file to android: layout_width = "wrap_content", the result is: button1 accounts for 1/3 and button2 accounts for 2/3.

What does this end mean? The following is a detailed explanation:

*********
When linearLayout contains weight child, linearLayout will be measure twice:
Set screen width to X
First time: the measuredWidth of button1 is X, and the value of button2 is X (because weight is used, linearLayout does not consider the previous occupied size for each measure child). total_width is 2X
Second: Calculate delta = x-total_width =-x, and then set the width of button1
X + delta * 1/3 = 0.66x, button2 is x + delta * 2/3 = 0.33x
Now I want to repeat this sentence: "because the minimum weight of button1 is set, the layout priority is higher ", maybe there is no priority in the layout of Android. I just want to illustrate the problem and define it myself, so don't make a brick.
First, analyze the layout_width setting to fill_parent, that is, filling the parent board, of course, this control requires the root setting of weight to be large. Therefore, based on the above example, weight of button1 is set to 1, set weight of button2 to 2. that is to say, the priority of the button is the highest. Therefore, to fill the parent board, button1 needs to be filled first. The priority may be large. What is the possibility of this priority, in this case, we need to combine the weight values of other controls in layout, and then perform the calculation. button1 has reached 2/3, and button2 has reached 1/3. you can also set button2 to a very large number, such as 2000. At this time, in Graphical Layout mode, you can see that button1 is filled with a whole degree of parallelism, without seeing the shadow of button2, actually button2 still exists. You can point the mouse pointer to the back of button1 and you will see a long comment, that is, button2, it's already very small. Therefore, when layout_width is set to fill_parent, weight indicates that your control must be larger first.

Then, when layout_weight is set to wrap_content, that is, the attention of the internal content, which means that the control may be small, you only need to display the content. In the same way, if you set the layout_weight of button1 and button2 to wrap_content, the weight of button1 is 1, the weight of button2 is 2. so button1 needs to begin with a smaller value, while button2 also needs a smaller value, but the difference is that when the first value is set to weight, therefore, the overall coverage of these two controls must be set to the coverage of the parent board. Therefore, we need to calculate the size of the memory size of each control. At this time, in button1, there are two parts, one is 1/3, one is 2/3, and the other is 1/3. If button1 needs to be renewed, it is possible that button1 should choose. Therefore, what we see is, in contrast, the greater the value of the button2 linear regression. In this case, if the permission value is set as follows: button1 is 1 and button2 is 2000, does button1 need to limit the space of 1/2000? This understanding is complete, and I just said that it is possible to reduce the size, but there is a limit for this small size, that is, wrap_content, that is, if the entire content is displayed, in the same way, there may be a limit to the maximum value, that is, the degree of attention of the Parent Board. Therefore, when layout_width is set to wrap_content, weight indicates that your control must be larger first.
Therefore, to understand weight, we need to deeply understand the following two sentences:
When layout_width is set to fill_parent, layout_weight indicates that your control needs to be scaled first, but this is limited, that is, fill_parent.
When layout_width is set to wrap_content, layout_weight indicates that your control needs to be scaled first, but this is limited, that is, wrap_content.

Layout_height is the same as layout_width.



The last few images are shown as follows:
1. layout_width = "fill_parent", weight of button1 = 1, weight of button2 = 2;




2. layout_width = "fill_parent", weight of button1 = 1, weight of button2 = 2000;



3. layout_width = "wrap_content", weight of button1 = 1, weight of button2 = 2;



4. layout_width = "wrap_content", weight of button1 = 1, weight of button2 = 2000;

* Reprint address: http://hi.baidu.com/ljlkings/blog/item/fa2a59803f839a82f603a6b2.html? Time stamp = 1305190390481

 

 

SDK description

 

Indicates how much ofExtra spaceIn the LinearLayout will be allocated to the view associated with these LayoutParams. Specify 0 if the view shoshould not be stretched. Otherwise the extra pixels will bePro-ratedAmong all views whose weight is greater than 0.

 

There are two important points. One is layout_weight, which indicates the division of additional space in LinearLayout (the size before layout_weight may be extended), and the other is proportional.

 

The following uses android: orientation = "horizontal" as an example.

 

Although I have read the source code, I do not quite understand it, but I have understood the general meaning and summarized it according to my own understanding, directly write the simplified code (the following code is a simplified part of the LinearLayout source file, and the variable name meaning may be inaccurate. For the sake of convenience, this explanation is provided ):

 

//Either expand children with weight to take up available space or// shrink them if they extend beyond our current boundsint delta = widthSize - mTotalLength;if (delta != 0 && totalWeight > 0.0f) {    float weightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight;    for (int i = 0; i < count; ++i) {        final View child = getVirtualChildAt(i);        if (child == null || child.getVisibility() == View.GONE) {            continue;        }                final LinearLayout.LayoutParams lp =                (LinearLayout.LayoutParams) child.getLayoutParams();        float childExtra = lp.weight;        if (childExtra > 0) {            int share = (int) (childExtra * delta / weightSum);       weightSum -= childExtra;        delta  -= share;
            int childWidth = child.getMeasuredWidth() + share;            if (childWidth < 0) {                childWidth = 0;            }        }    }}

 

Variable meaning

 

WidthSize: the width of LinearLayout.

 

MTotalLength: Sum of the width of all sub-views (layout_weight is not considered)

 

TotalWeight: Sum of layout_weight of all child views

 

Android: weightSum attribute of mWeihtSUm: LinearLayout

 

Process Analysis:

 

First, the extra space (which can be negative) is calculated. If the extra space is not 0 and the layout_weight of a sub-View is not 0, the extra space will be allocated based on layout_weight:

 

int delta = widthSize - mTotalLength;if (delta != 0 && totalWeight > 0.0f) {  ...}

 

If weightSum is set for LinearLayout, the sum of layout_weight of the sub-View is overwritten:

 

float weightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight;

 

Then traverse the child element of LinearLayout. If it is not null and Visibility is not GONE, obtain its LayoutParams. If its layout_weight is greater than 0, calculate the extra space allocated to weightSum based on its weight.

 

if (childExtra > 0) {    int share = (int) (childExtra * delta / weightSum);   weightSum -= childExtra;   delta -= share;    int childWidth = child.getMeasuredWidth() + share;    if (childWidth < 0) {        childWidth = 0;    }}

 


It is explained on the Internet that layout_weight indicates the importance and the priority of additional space. It is wrong to know this idea through code. layout_weight indicates the proportion of the partition. As for the inverse of layout_weight ratio when layout_width of the View is fill_parent, I can explain the following:

 

For example, the following XML:

 

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:background="#00ff00"    android:weightSum="0"    android:orientation="horizontal" >    <Button        android:id="@+id/imageViewLoginState"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_weight="1"        android:text="1" >    </Button>    <Button        android:id="@+id/imageViewLoginState1"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_weight="1"        android:text="2" >    </Button>    <Button        android:id="@+id/imageViewLoginState2"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_weight="2"        android:text="3" >    </Button></LinearLayout>

 



 

Generally, the ratio of the three buttons should be, but the actual situation is as follows:

 

 

In my understanding, the system sets the button size in this way, and the variable name follows the meaning of the previous Code:

 

Assume that the Container (LinearLayout) width is PARENT_WIDTH.

 

The width of the three buttons is FILL_PARENT. Therefore, before layout_width is applied, the width of the three buttons is PARENT_WIDTH.

 

So the extra space delta = PARENT_WIDTH-3 * PARENT_WIDTH =-2 * PARENT

 

Because android: weightSum is not set for LinearLayout (the default value is 0 and it is set to 0), mWeightSum = 1 + 1 + 2 = 4

 

Therefore:

 

The width of the first button is PARENT_WIDTH + share = PARENT_WIDTH + (layout_weight * delta/mWeightSum) = PARENT_WIDTH + (1*(-2 * PARENT_WIDTH)/4) = 1/2 * PARENT_WIDTH

 

    weightSum -= childExtra;(=3)    delta  -= share;(=-3/2 * PARENT_WIDTH)

 

The width of the second button is PARENT_WIDTH + share = PARENT_WIDTH + (layout_weight * delta/mWeightSum) = PARENT_WIDTH + (1*(-3/2 * PARENT_WIDTH)/3) = 1/2 * PARENT_WIDTH

 

    weightSum -= childExtra;(=2)    delta  -= share;(=-PARENT_WIDTH)

 

The width of the third button is PARENT_WIDTH + share = PARENT_WIDTH + (layout_weight * delta/mWeightSum) = PARENT_WIDTH + (2 * (-PARENT_WIDTH)/2) = 0

 

So in the end, the first two buttons are evenly divided into LinearLayout, and the third button disappears.

 

 

 

The general process is as follows, but not all. For example, if the weightSum of LinearLayout in the preceding example is set to 2, the width of the first two buttons is 0, however, when the width of the third button is calculated as mWeightSum = 0, layout_weight * delta/mWeightSum cannot be calculated, and the system does not know how to handle it. It is out of my ability, when weightSum is 2:

 

 

When weightSum is 3:

 

 

 

 

In the SDK, layout_weight indicates how to divide the extra space. Pay attention to the additional two words. You need additional space to allocate it to the subview with layout_weight configured in proportion, therefore, if LinearLayout is set to WRAP_CONTENT, there is no extra space, and layout_weight is useless. As long as layout_width is not set to WRAP_CONTENT, it can also be set to a specific value, if the value is too small, the extra space is negative, and the Child control may be compressed to make it smaller than the size defined in the XML file. For example:

 

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="100dp"    android:layout_height="wrap_content"    android:background="#00ff00"    android:orientation="horizontal" >    <Button        android:id="@+id/button1"        android:layout_width="60dp"        android:layout_height="fill_parent"        android:layout_weight="1"        android:text="1" >    </Button>    <Button        android:id="@+id/button2"        android:layout_width="60dp"        android:layout_height="fill_parent"        android:layout_weight="1"        android:text="2" >    </Button>    <Button        android:id="@+id/button3"        android:layout_width="60dp"        android:layout_height="fill_parent"        android:layout_weight="2"        android:text="3" >    </Button></LinearLayout>

 

Extra space delta = 100-3*60 =-80

 

MWeightSum = 1 + 1 + 2 = 4

 

Therefore:

 

The width of the first button is 60 + share = 60 + (layout_weight * delta/mWeightSum) = 60 + (1 * (-80)/4) = 40

 

    weightSum -= childExtra;(=3)    delta  -= share;(=-60)

 

The width of the second button is 60 + share = 60 + (layout_weight * delta/mWeightSum) = 60 + (1 * (-60)/3) = 40

 

    weightSum -= childExtra;(=2)    delta  -= share;(=-40)

 

The width of the third button is 60 + share = 60 + (layout_weight * delta/mWeightSum) = 60 + (2 * (-40)/2) = 20

 

:

 

 

 

 

The following code also shows that layout_weight indicates the allocation of extra space:

 

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="200dp"    android:layout_height="wrap_content"    android:background="#00ff00"    android:orientation="horizontal" >    <Button        android:id="@+id/button1"        android:layout_width="60dp"        android:layout_height="fill_parent"        android:layout_weight="1"        android:text="1" >    </Button>    <Button        android:id="@+id/button2"        android:layout_width="40dp"        android:layout_height="fill_parent"        android:layout_weight="1"        android:text="2" >    </Button>   </LinearLayout>

The extra space is 100, so the width of Button1 is 60 + 100/2 = 110, and the width of Button2 is 40 + 100/2 = 90


Android: layout_weight in the LinearLayout Layout

Learn from you !~~ This test is thorough enough !~~ Hope you can find the answer !~~

The sub-element attribute android: layout_weight in LinearLayout has other features.

I don't know what you are asking. I currently use this property. For example, one row has two controls, and each control
Android: layout_weight = "1" and they will divide the region equally.
For example, if you have a TextView, the following ListView only needs to set android: layout_weight = "1" for the listview to make the textview not covered during the listview drop-down.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.