Programming

안드로이드에서 android : weightSum은 무엇이며 어떻게 작동합니까?

procodes 2020. 6. 9. 22:48
반응형

안드로이드에서 android : weightSum은 무엇이며 어떻게 작동합니까?


알고 싶습니다 : android : weightSum 및 레이아웃 가중치 란 무엇이며 어떻게 작동합니까?


문서 당 android:weightSum최대 무게 합계를 정의하고 layout_weight명시 적으로 지정하지 않은 경우 모든 자식 의 합계로 계산됩니다 .

LinearLayout가로 방향이 있고 그 ImageViews안에 3이 있는 예를 생각해 봅시다 . 이제 우리는 이것들이 ImageViews항상 같은 공간을 차지하기를 원합니다 . 이것을 달성하기 위해, 당신 layout_weight은 각각 ImageView을 1로 설정할 수 weightSum있으며 주석에 표시된 것처럼 3은 3과 같이 계산됩니다.

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    <!-- android:weightSum="3" -->
    android:orientation="horizontal"
    android:layout_gravity="center">

   <ImageView
       android:layout_height="wrap_content"       
       android:layout_weight="1"
       android:layout_width="0dp"/>
  .....

weightSum 너비와 높이를 직접 설정하면 발생하지 않는 모든 장치에 대해 레이아웃을 올바르게 렌더링하는 데 유용합니다.


superM과 Jeff의 답변에 덧붙여서

LinearLayout에 두 개의 뷰가있는 경우, 첫 번째는 layout_weight가 1이고 두 번째는 layout_weight가 2이고 weightSum이 지정되지 않은 경우 기본적으로 weightSum은 3 (자식 가중치의 합)으로 계산됩니다. 첫 번째 뷰는 공간의 1/3을 차지하고 두 번째 뷰는 2/3을 차지합니다.

그러나 weightSum을 5로 지정하면 첫 번째는 공간의 1/5을 차지하고 두 번째는 2/5를 차지합니다. 따라서 나머지 공간을 비워 두는 레이아웃이 총 3/5의 공간을 차지합니다.


가중치 합계는 원하는대로 정확하게 작동합니다 (다른 답변과 마찬가지로 부모 레이아웃의 모든 가중치를 합계 할 필요는 없습니다). 자식보기에서 원하는 무게를 지정하십시오. 잊지 말고 지정하십시오

android:layout_width="0dp" 

다음은 예입니다

    <LinearLayout
                android:layout_width="500dp"
                android:layout_height="20dp" >

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="3"
                    android:background="@android:color/holo_green_light"
                    android:gravity="center"
                    android:text="30%"
                    android:textColor="@android:color/white" >
                </TextView>

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="2"
                    android:background="@android:color/holo_blue_bright"
                    android:gravity="center"
                    android:text="20%"
                    android:textColor="@android:color/white" >
                </TextView>

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="5"
                    android:background="@android:color/holo_orange_dark"
                    android:gravity="center"
                    android:text="50%"
                    android:textColor="@android:color/white" >
                </TextView>
 </LinearLayout>

이것은 다음과 같이 보일 것입니다

enter image description here


The documentation says it best and includes an example, (highlighting mine).

android:weightSum

Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.

So to correct superM's example, suppose you have a LinearLayout with horizontal orientation that contains two ImageViews and a TextView with. You define the TextView to have a fixed size, and you'd like the two ImageViews to take up the remaining space equally.

To accomplish this, you would apply layout_weight 1 to each ImageView, none on the TextView, and a weightSum of 2.0 on the LinearLayout.


After some experimenting, I think the algorithm for LinearLayout is this:

Assume that weightSum is set to a value. The case of absence is discussed later.

First, divide the weightSum by the number of elements whith match_parent or fill_parent in the dimension of the LinearLayout (e.g. layout_width for orientation="horizontal"). We will call this value the weight multiplier w_m for each element. The default value for weightSum is 1.0, so the default weight multiplier is 1/n, where n is the number of fill_parent elements; wrap_content elements do not contribute to n.

w_m = weightSum / #fill_parent

E.g. when weightSum is 60, and there are 3 fill_parent elements, the weight multiplier is 20. The weight multiplier is the default value for e.g. layout_width if the attribute is absent.

Second, the maximum possible expansion of every element is computed. First, the wrap_content elements are computed according to their contents. Their expansion is deducted from the expansion of the parent container. We will call the remainer expansion_remainer. This remainder is distributed among fill_parent elements according to their layout_weight.

Third, the expansion of every fill_parent element is computed as:

w_m - ( layout_weight / w_m ) * maximum_possible_expansion

Example:

If weightSum is 60, and there are 3 fill_parent elements with the weigths 10, 20 and 30, their expansion on the screen is 2/3, 1/3 and 0/3 of the parent container.

weight | expansion
     0 | 3/3
    10 | 2/3
    20 | 1/3
    30 | 0/3
    40 | 0/3

The minimum expansion is capped at 0. The maximum expansion is capped at parent size, i.e. weights are capped at 0.

If an element is set to wrap_content, its expansion is calculated first, and the remaining expansion is subject to distribution among the fill_parent elements. If weightSum is set, this leads to layout_weight having no effect on wrap_content elements. However, wrap_content elements can still be pushed out of the visible area by elements whose weight is lower than weight multiplier (e.g. between 0-1 for weightSum= 1 or between 0-20 for the above example).

If no weightSum is specified, it is computed as the sum of all layout_weight values, including elements with wrap_content set! So having layout_weight set on wrap_content elements, can influence their expansion. E.g. a negative weight will shrink the other fill_parent elements. Before the fill_parent elements are laid out, will the above formula be applied to wrap_content elements, with maximum possible expansion being their expansion according to the wrapped content. The wrap_content elements will be shrunk, and afterwards the maximum possible expansion for the remaining fill_parent elements is computed and distributed.

This can lead to unintuitive results.


If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0. Must be a floating point value, such as "1.2"

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/main_rel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:weightSum="2.0" >

        <RelativeLayout
            android:id="@+id/child_one"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1.0"
            android:background="#0000FF" >
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/child_two"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1.0"
            android:background="#00FF00" >
        </RelativeLayout>

    </LinearLayout>

One thing which seems like no one else mentioned: let's say you have a vertical LinearLayout, so in order for the weights in layout/element/view inside it to work 100% properly - all of them must have layout_height property (which must exist in your xml file) set to 0dp. Seems like any other value would mess things up in some cases.


From developer documentation

This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.

Addition to @Shubhayu answer

rest 3/5 can be used for other child layouts which really doesn't need any specific portion of containing layout.

this is potential use of android:weightSum property.


Layout Weight works like a ratio. For example, if there is a vertical layout and there are two items(such as buttons or textviews), one having layout weight 2 and the other having layout weight 3 respectively. Then the 1st item will occupy 2 out of 5 portion of the screen/layout and the other one 3 out of 5 portion. Here 5 is the weight sum. i.e. Weight sum divides the whole layout into defined portions. And Layout Weight defines how much portion does the particular item occupies out of the total Weight Sum pre-defined. Weight sum can be manually declared as well. Buttons, textviews, edittexts etc all are organized using weightsum and layout weight when using linear layouts for UI design.

참고URL : https://stackoverflow.com/questions/7452741/what-is-androidweightsum-in-android-and-how-does-it-work

반응형