ConstraintLayout :: 사용설명서 1탄

Geon
cashwalk
Published in
6 min readDec 27, 2018

ConstraintLayout 👈 공식사이트

  • 2016 Google I/O에서 처음 발표되었고 2017년 1.0이 배포 되었습니다(2017.02)
  • 현재는 2.0 Alpha 까지 배포가 되어있습니다. (2018.06)
  • RelativeLayout과 사용법이 비슷하지만 좀 더 유연한 기능들을
    갖추고있습니다.
  • 단순한 계층구조를 이룰 수 있어 다른 레이아웃에 비해 유지보수가
    좋습니다.

ConstraintLayout 1.1.3버전 기준으로 작성했으며

실제 사용해본 기준으로 먼저 작성할 예정입니다.

원하는곳에 위치시키기

<ImageView
android:id="@+id/imageView" ...
app:layout_constraintRight_toRightOf="parent" />

위에 ImageView를 보면 app:layout_constraintRight_toRightOf=”parent” 라는 옵션이 존재합니다. ConstraintLayout에서 기본적으로 쓰이는 옵션중에 하나이며 단순한 계층을 이루는데 기초가 되는 옵션입니다.

app:layout_constraintRight(1)_toRight(2)Of="parent"

옵션의 의미를 보면 “ImageView의 right(1)를 parent의 right(2)에 제약을 걸겠다” 라는 의미입니다. 즉 parent의 right면에 ImageView의 right면을 위치시키겠다라는 옵션입니다. 해당 옵션을 주게되면 옵션의 의미와 같이 뷰가 배치되는 것을 볼 수 있습니다.

parent의 right로 움직이는 모습

옵션의 종류는 아래와 같습니다.

    app:layout_constraintBottom_toBottomOf
app:layout_constraintBottom_toTopOf
app:layout_constraintLeft_toLeftOf
app:layout_constraintLeft_toRightOf
app:layout_constraintRight_toLeftOf
app:layout_constraintRight_toRightOf
app:layout_constraintTop_toBottomOf
app:layout_constraintTop_toTopOf

이러한 옵션들을 통해서 원하는곳은 물론 중앙에도 배치시킬 수 있습니다.

그룹화하기 (Chain)

Chain은 최소 두 개 이상의 뷰들을 그룹처럼 움직일 수 있도록 해줍니다.
Chain은 가로축 또는 세로축으로 그룹 지을 수 있습니다.

방법은 간단합니다. 뷰들을 서로 연결시켜 주기만 하면 됩니다.

<ImageView
android:id="@+id/imageView" ...
app:layout_constraintRight_toLeftOf="@id/textView" />

<TextView
android:id="@+id/textView" ...
app:layout_constraintLeft_toRightOf="@id/imageView" />

이렇게 연결을 시켜주면

서로 연결한 뷰 사이에 체인이 연결되는 것을 확인 할 수 있습니다.
체인으로 연결되면 여백이 생기게되는데 여백은 ChainStyle에 의해 조절이
가능합니다.

    app:layout_constraintHorizontal_chainStyle=""
app:layout_constraintVertical_chainStyle=""

ChainStyle 위 코드와 같이 Horizontal과 Vertical이 있으며, Chain의 HEAD에
주어야 됩니다.

HEAD는 가장 왼쪽(가로축 기준) 또는 가장 위쪽(세로축 기준)입니다.
Style의 종류는 spread, spread_inside, packed로 총 3가지 입니다.

  • spread
기본 스타일이며 동일한 사이즈의 여백을 갖습니다.
  • spread_inside
양쪽 바깥자리의 뷰들이 가장자리에 배치되고 남은사이 공간에 나머지 뷰들이 배치가 됩니다.
  • packed
연결된 뷰들이 가운데로 배치됩니다.
  • Weighted Chain

LinearLayout에서 weight를 줘서 배치하는 방법과 같은 동작을 하는
옵션입니다.

    app:layout_constraintHorizontal_weight=""
app:layout_constraintVertical_weight=""

위 코드와 같이 생겼으며 옵션을 주고싶은 뷰마다 선언을 해줘야하며
android:layout_width=”0dp”로 지정을 해줘야 정상 작동을 합니다.

왼쪽부터 Weight 3, 2, 1을 준 모습입니다.

ConstraintLayout에는 수많은 옵션들이 존재하지만 지금까지 나온 옵션들로도 충분히 UI를 만들 수 있습니다.
적응기간과 옵션에 대한 조금의 난이도가 있지만 충분히 매력있는
레이아웃 입니다.

2탄 작성 예정입니다!

to be continued…

--

--