Android # Constraint Layout(제약 레이아웃)
카테고리 없음

Android # Constraint Layout(제약 레이아웃)

Constraint Layout(제약 레이아웃)

  • 제약 레이아웃의 가장 큰 특징은 뷰의 크기와 위치를 결정할 때, 제약 조건(Constraint)를 사용한다는 것.
  • 제약 조건이란 뷰가 레이아웃 안의 다른 요소와 어떻게 연결되는지 알려주는 것.
  • 뷰의 연결점(Anchor Point)과 대상(Target)을 연결.
  • 마진(Margin) : 연결점과 타깃과의 거리를 나타냄.
  • 가로 바이어스(Horizontal Bias)/ 세로 바이어스(Vertical Bias)를 사용하면 화면을 비율로 나눈 곳에 위치시킬 수 있음.
  • 뷰를 담고 있는 부모 레이아웃 안에서 크기나 위치를 자유롭게 조절할 수 있음.

대상(Target)이 될 수 있는 것

  1. 같은 부모 레이아웃 안에 들어있는 다른 뷰의 연결점
  2. 부모 레이아웃의 연결점
  3. 가이드라인(Guideline)

대상 뷰와 타깃의 연결점이 될 수 있는 것

  1. 위쪽(Top), 아래쪽(Bottom), 왼쪽(Left), 오른쪽(Right)
  2. 가로축의 가운데(CentetX), 세로축의 가운데(CenterY)
  3. 베이스라인(Baseline) → 텍스트를 보여주는 뷰인 경우에만 적용됨

가이드라인 사용하기

  1. res>layout 폴더 선택 후, 우클릭 [new → Layout resource file]
  2. XML 레이아웃 파일 이름 입력
  3. RootElement: 입력상자에 android:support.constraint.ConstraintLayout 입력 후 OK 버튼 눌러 생성
  4. 디자인 화면 위쪽에 위치한 [Guidelines]아이콘 클릭
  5. 가로/세로 방향 선택(add Horizontal Guidelines/add Vertical Guidelines)
  6. 추가된 가이드라인을 이동시키면 위치 조절이 가능.

생성된 가이드라인에 연결점으로 타겟지정을 할 수 있다.

위의 xml의 코드를 보면 다음과 같다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="70dp" />
 
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/button4" />
 
    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/button5" />
</androidx.constraintlayout.widget.ConstraintLayout>
cs