안드로이드에서 LinearLayout에 weight

조회수 16909회

안드로이드 문서를 읽다가 weight라는 재밌는 속성을 발견했는데요. 그래서 그걸 적용해보려고 간단한 레이아웃을 작성했어요.

  <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

  </LinearLayout>

가로로 정렬해서 두 버튼이 반반씩 width를 나눠가지게끔 하려고했는데 실행해보니까 둘다 제대로 보여지지 않아요. 첫번째버튼만 한줄을 꽉채워서 출력되는데 뭐가 잘못된건가요?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    일단 weight는 비율을 주는 속성인데 width나 height중 비율을 주고싶은 속성에 0dp를 줘야합니다. 여기선 한줄을 똑같이 나눠가지길 원하니까 width의 값에 0dp를 주어야합니다. 또 항목들을 감싸고 있는 레이아웃에 weigthSum값을 지정해주어야하는데 이거는 선택사항입니다. weight는 비율 값이라 0.00~1.00까지의 값을 가집니다. 위에서 똑같이 두 버튼에 1, 1의 값을 주셨는데 반반이 나오길 원하신다면 weightSum의 값을 2로 주시는게 맞습니다.

    weight는 weightSum의 값을 기준으로 그 비율만큼 자리를 차지하게 하는 속성입니다. 예를들어

        <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="5">
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="1" />
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:text="2" />
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="3" />
    
        </LinearLayout>
    

    이런식으로 했다면 출력결과는

    1

    이렇게 될것입니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)