개요

android:weight 속성은 부모 레이아웃의 남은 공간을 뷰들 간에 어떻게 분배할지 결정하는 데 사용됩니다. 즉, 가중치를 기반으로 뷰들이 화면에서 차지하는 공간의 비율을 조정할 수 있습니다.

**android:orientation="horizontal"**으로 설정되어 있고, 두 개의 **Button**이 있을 경우, 각각의 android:layout_width 속성을 **"0dp"**로 설정하고 android:weight 속성을 각각 **"1"**로 설정한다면, 두 개의 **Button**은 동일한 가로 공간을 차지하게 됩니다. 이때 가중치 값이 더 큰 뷰는 더 많은 공간을 차지하게 됩니다.

가중치를 사용하면 화면 크기가 다른 디바이스에서도 유연한 레이아웃을 구성할 수 있습니다. 예를 들어, 가중치를 사용하여 화면의 너비를 비율로 조정하면 화면의 크기에 관계없이 뷰들이 적절한 비율로 나란히 표시됩니다.

주의할 점은 android:layout_width 또는 android:layout_height 속성을 **"0dp"**로 설정해야 가중치가 제대로 작동합니다. 뷰의 크기를 **wrap_content**로 설정하면 가중치가 무시되고 해당 뷰의 내용에 맞게 크기가 결정됩니다.

요약하자면, android:weight 속성은 뷰들 간에 부모 레이아웃의 공간을 어떻게 분배할지를 결정하는데 사용되는 가중치 값을 지정하는 속성입니다.

방법

Untitled

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="<http://schemas.android.com/apk/res/android>"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button 2" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 3" />

</LinearLayout>

위의 코드에서는 android:layout_weight 속성을 사용하여 가중치를 설정했습니다. android:layout_width 속성을 **"0dp"**로 설정하여 가중치가 제대로 작동하도록 합니다.

각 버튼에 android:layout_weight 속성을 할당했는데, 첫 번째와 세 번째 버튼에는 **"1"**의 가중치를, 두 번째 버튼에는 **"2"**의 가중치를 지정했습니다. 이 경우 첫 번째와 세 번째 버튼은 동일한 가중치를 가지므로 부모 레이아웃의 나머지 공간을 동일하게 나눠 가지게 됩니다. 그리고 두 번째 버튼은 가중치가 더 크므로 더 많은 공간을 차지합니다.

결과적으로, **android:weight**를 사용한 경우, 가중치에 따라 버튼들이 가로로 나란히 표시되지만, 가중치가 없는 경우에는 각 버튼의 크기에 따라 동적으로 조정됩니다. **android:weight**를 사용하면 화면 크기에 관계없이 버튼들의 비율을 유지하면서 유연한 레이아웃을 구성할 수 있습니다.