본문 바로가기

나의 플랫폼/안드로이드

[Android] LinearLayout 에서 layout_weight를 사용할 때

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Linearlayout에서 layout_weight가 무엇인지는 대부분 잘 아실 꺼라 생각 됩니다.


layout_weight에 대해 궁금 하신 분들은 구글에서 layout_weight 라고 검색만 해도 글이 엄청 많습니다.

이번 글에서는 layout_weight에 대한 설명은 하지 않습니다.


그럼 어떤 내용이냐...


예를 들어 아래와 같은 상황이 있습니다.


--------------------------------------------------

LinearLayout : horizontal                     |

   --------------------------------------------   |

   |      TextView    |      ImageView  |    |

   --------------------------------------------   |

--------------------------------------------------


위와 같이 가로 형태의 LinearLayout 안에 TextView와 ImageView가 있습니다.


만약 TextView가 너무 길어지게 되면 ImageView가 LinearLayout 밖으로 나가게 되어 보이지 않죠.

그럴 경우 layout_weight를 아래와 같이 사용 하면


<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.0"

android:layout_marginRight="9dp"
android:layout_marginEnd="9dp"
android:maxLines="1"
android:ellipsize="end" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"/>
</LinearLayout>


ImageView는 밀리지 않고 TextView 크기에 따라 고정이 되는 것이죠.


여기서 LinearLayout에서 layout_width를 wrap_content로 둔 이유는

만약 match_parent로 할 경우 무조건 남는 사이즈를 TextView가 가지고 가기 때문에

TextView가 text 값과 상관 없이 풀 사이즈가 되는 것이죠.

그래서 ImageView가 밀리지는 않겠지만, 우측 가장자리에서 고정이 되겠죠.


여기 까지 읽으시고, 아니 이게 머~ 하시는 분들이 있을 수도 있으실 겁니다.

layout_weight를 아시는 분들이라면 쉽게 생각 할 수 있는 구조 거든요.


근데!!! 제가 이글을 쓴 이유는!

Lollipop(v21) 이상에서 정상 동작이 이뤄지지 않을 때가 있었습니다.

TextView 사이즈가 text 만큼 벌어지지 않고 더 적게 설정될 때가 생겨,

TextView에 text가 짤리는 현상이 일어납니다.


그럼 어떻게 하느냐!

아래와 같이 하니 잘 되더군요.



<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"

android:layout_marginRight="9dp"
android:layout_marginEnd="9dp"
android:maxLines="1"
android:ellipsize="end" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"/>
</LinearLayout>

TextView에서 0dp로 했던 부분을 wrap_content로 변경 합니다.!


그럼 TextView에서 text가 짤리는 현상이 없어지더라구요.

wrap_content에서 기본 사이즈를 잡아줘서 그런듯 합니다.


그럼 혹시 ellipsize가 제대로 동작하지 않거나 ImageView가 사라지는 현상이 발생 할수도 있지 않을까??

테스트 해본 결과 문제 없이 동작 합니다.


혹시 저와 같이 TextView가 짤리는 현상이 있으신 분은 참고 해보세요.