웹사이트 검색

Android 레이아웃 - LinearLayout, RelativeLayout


이 튜토리얼에서는 Android 레이아웃에 대한 개요를 제공합니다. 또한 Android LinearLayout 및 Android RelativeLayout과 같은 화면 콘텐츠를 구성하는 데 사용할 수 있는 특정 레이아웃 컨트롤 중 일부를 살펴보겠습니다.

안드로이드 레이아웃

사용자 인터페이스의 기본 빌딩 블록은 View 클래스에서 생성되고 화면의 직사각형 영역을 차지하는 View 개체입니다. 뷰는 TextView, Button, EditText 등과 같은 UI 구성 요소의 기본 클래스입니다. ViewGroup은 View의 하위 클래스입니다. 하나 이상의 View를 ViewGroup으로 함께 그룹화할 수 있습니다. ViewGroup은 뷰의 모양과 순서를 정렬할 수 있는 Android 레이아웃을 제공합니다. ViewGroup의 예는 LinearLayout, FrameLayout, RelativeLayout 등입니다.

Android 레이아웃 유형

Android는 다음과 같은 ViewGroup 또는 레이아웃을 제공합니다.

  1. LinearLayout : 모든 자식을 세로 또는 가로로 한 방향으로 정렬하는 ViewGroup입니다.
  2. RelativeLayout : 상대 위치에 하위 뷰를 표시하는 ViewGroup입니다.
  3. AbsoluteLayout : 자식 뷰와 위젯의 정확한 위치를 지정할 수 있습니다.
  4. TableLayout : 하위 뷰를 행과 열로 그룹화하는 뷰입니다.
  5. FrameLayout : 단일 보기를 표시하는 데 사용되는 화면의 자리 표시자입니다.
  6. ScrollView : 사용자가 실제 디스플레이보다 더 많은 공간을 차지하는 보기 목록을 스크롤할 수 있도록 하는 특별한 유형의 FrameLayout입니다. ScrollView는 일반적으로 LinearLayout인 하나의 하위 보기 또는 ViewGroup만 포함할 수 있습니다.
  7. ListView : 스크롤 가능한 항목 목록을 표시하는 뷰 그룹입니다.
  8. GridView : 2차원 스크롤 그리드에 항목을 표시하는 ViewGroup입니다. 그리드의 항목은 이 보기와 연결된 ListAdapter에서 가져옵니다.

이 튜토리얼에서는 가장 많이 사용되는 두 가지 Android 레이아웃에 초점을 맞출 것입니다.

  1. 선형 레이아웃
  2. 상대 레이아웃

Android 레이아웃 속성

  1. android:id : 보기를 고유하게 식별하는 ID입니다.
  2. android:layout_width : 레이아웃의 너비입니다.
  3. android:layout_height : 레이아웃의 높이입니다.
  4. android:layout_margin : 뷰 외부의 추가 공간입니다. 예를 들어 android:marginLeft=20dp를 지정하면 보기가 왼쪽에서 20dp 뒤에 정렬됩니다.
  5. android:layout_padding : 이것은 뷰 내부에 추가 공간을 지정한다는 점을 제외하면 android:layout_margin과 유사합니다.
  6. android:layout_gravity : 하위 뷰가 배치되는 방식을 지정합니다.
  7. android:layout_weight : 레이아웃의 추가 공간을 뷰에 할당해야 하는 정도를 지정합니다.
  8. android:layout_x : 레이아웃의 x 좌표를 지정합니다
  9. android:layout_y : 레이아웃의 y 좌표를 지정합니다.

android:layout_width=wrap_content는 콘텐츠에 필요한 크기로 자체 크기를 조정하도록 뷰에 지시합니다. android:layout_width=match_parent는 뷰가 상위 뷰만큼 커지도록 지시합니다.

신분증 보기

XML 태그 내부의 ID 구문은 다음과 같습니다.

  • 문자열 시작 부분의 at 기호(@)는 XML 파서가 ID 문자열의 나머지 부분을 구문 분석하고 확장하여 ID 리소스로 식별해야 함을 나타냅니다.
  • 더하기 기호(+)는 이것이 생성되어 리소스에 추가되어야 하는 새 리소스 이름임을 의미합니다.

Android 선형 레이아웃

Android LinearLayout은 한 줄을 따라 요소를 구성합니다. android:orientation을 사용하여 해당 선이 수직인지 수평인지 지정할 수 있습니다. 방향은 기본적으로 수평입니다. 수직 LinearLayout은 행당 하나의 자식만 가지며(따라서 단일 요소의 열임) 수평 LinearLayout은 화면에 요소의 단일 행만 갖습니다. android:layout_weight 속성은 요소의 중요성을 나타냅니다. 가중치가 큰 요소는 더 많은 화면 공간을 차지합니다. 다음은 LinearLayout을 사용하는 샘플 레이아웃 XML입니다. layout_linear.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="@dimen/activity_horizontal_margin">
    <Button
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:text="Row 2"
        android:layout_width="wrap_content"
        android:textSize="18sp"
        android:layout_margin="10dp"
        android:layout_height="wrap_content" />
    <TextView
        android:text="Row 3"
        android:textSize="18sp"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:text="Row 4"
        android:textSize="18sp"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:text="Row 5"
        android:textSize="18sp"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/next_button"
            android:text="next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:text="Row 6b"
            android:textSize="18sp"
            android:layout_margin="10dp"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:text="Row 6c"
            android:textSize="18sp"
            android:layout_margin="10dp"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:text="Row 6d"
            android:textSize="18sp"
            android:layout_margin="10dp"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

</LinearLayout>

이 레이아웃에는 세로 방향이 있고 버튼, 텍스트 뷰 및 하위 보기로 중첩된 선형 레이아웃(가로 방향이 있음)을 포함하는 부모 LinearLayout이 있습니다. 참고: 중첩된 레이아웃은 한 유형일 필요가 없습니다. 예를 들어 LinearLayout을 RelativeLayout의 자식 중 하나로 가질 수 있으며 그 반대의 경우도 마찬가지입니다.

안드로이드 상대 레이아웃

Android RelativeLayout은 요소 간의 관계 및 상위 컨테이너와의 관계를 기반으로 요소를 배치합니다. 이것은 가장 복잡한 레이아웃 중 하나이며 실제로 원하는 레이아웃을 얻으려면 여러 속성이 필요합니다. 즉, RelativeLayout을 사용하여 뷰를 toLeftOf, toRightOf, 형제 아래 또는 위에 배치할 수 있습니다. 또한 수평, 수직 또는 양쪽 중앙에 배치하거나 부모 RelativeLayout의 가장자리에 정렬하는 것과 같이 부모를 기준으로 뷰를 배치할 수 있습니다. 하위 보기에 이러한 속성이 지정되지 않은 경우 보기는 기본적으로 왼쪽 상단 위치에 렌더링됩니다.

안드로이드 RelativeLayout 속성

다음은 RelativeLayout에서 사용되는 주요 속성입니다. 그들은 세 가지 범주에 걸쳐 있습니다.

컨테이너에 상대적

  • android:layout_alignParentBottom : 요소의 하단을 컨테이너 하단에 배치
  • android:layout_alignParentLeft : 요소의 왼쪽을 컨테이너의 왼쪽에 배치
  • android:layout_alignParentRight : 요소의 오른쪽을 컨테이너의 오른쪽에 배치
  • android:layout_alignParentTop : 컨테이너 상단에 요소 배치
  • android:layout_centerHorizontal : 부모 컨테이너 내에서 수평으로 요소를 중앙에 배치
  • android:layout_centerInParent : 요소를 컨테이너 내에서 수평 및 수직으로 중앙에 배치합니다.
  • android:layout_centerVertical : 요소를 부모 컨테이너 내에서 수직으로 중앙에 배치

형제자매 관련

  • android:layout_above : 지정된 요소 위에 요소 배치
  • android:layout_below : 지정된 요소 아래에 요소 배치
  • android:layout_toLeftOf : 지정된 요소의 왼쪽에 요소 배치
  • android:layout_toRightOf : 지정된 요소의 오른쪽에 요소를 배치합니다.

"@id/XXXXX\는 id로 요소를 참조하는 데 사용됩니다. 한 가지 기억해야 할 점은 요소가 선언되기 전에 참조하면 오류가 발생하므로 이러한 경우 @+id/를 사용해야 합니다.

다른 요소와의 정렬

  • android:layout_alignBaseline : 새 요소의 기준선을 지정된 요소의 기준선에 맞춥니다.
  • android:layout_alignBottom : 새 요소의 아래쪽을 지정된 요소의 아래쪽에 맞춥니다.
  • android:layout_alignLeft : 새 요소의 왼쪽 가장자리를 지정된 요소의 왼쪽 가장자리에 맞춥니다.
  • android:layout_alignRight : 새 요소의 오른쪽 가장자리를 지정된 요소의 오른쪽 가장자리에 맞춥니다.
  • android:layout_alignTop : 새 요소의 상단을 지정된 요소의 상단에 정렬

다음 xml 레이아웃은 RelativeLayout을 사용합니다. layout_relative.xml

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/firstName"
        android:text="First Name"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/backbutton" />
    <TextView
        android:id="@+id/editFirstName"
        android:text="JournalDev"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/firstName"
        android:layout_below="@id/backbutton"/>
    <TextView
        android:id="@+id/editLastName"
        android:text="Layout Tutorial Example"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/lastName"
        android:layout_toRightOf="@+id/lastName"
        android:layout_toEndOf="@+id/lastName" />
    <TextView
        android:id="@+id/lastName"
        android:text="Last Name"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:layout_below="@+id/firstName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="40dp"
        android:layout_marginStart="40dp" />

    <Button
        android:id="@+id/next"
        android:text="Next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editLastName"
        android:layout_alignLeft="@+id/editLastName"
        android:layout_alignStart="@+id/editLastName"
        android:layout_marginTop="37dp" />
</RelativeLayout>

보시다시피 상대적인 위치에 따라 요소를 재정렬할 수 있습니다. 다음 xml 레이아웃은 중첩된 선형 및 상대 레이아웃이 있는 사용자 지정 레이아웃을 나타냅니다. layout_mixed.xml

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/parent_rl"
        android:text="Parent RelativeLayout"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout"
        android:layout_below="@id/parent_rl"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true">

        <TextView
            android:text="Nested Horizontal"
            android:textSize="18sp"
            android:layout_margin="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:text="LL"
            android:textSize="18sp"
            android:layout_margin="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:text="Double Nested"
                android:textSize="18sp"
                android:layout_margin="10dp"
                android:layout_gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <TextView
                android:text="Vertical"
                android:textSize="18sp"
                android:layout_margin="10dp"
                android:layout_gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <TextView
                android:text="LL"
                android:textSize="18sp"
                android:layout_margin="10dp"
                android:layout_gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>


    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/linearLayout">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Nested Relative Layout"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

        <Button
            android:id="@+id/back_button_pressed"
            android:text="back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="66dp" />

    </RelativeLayout>


</RelativeLayout>

Android 레이아웃 프로젝트 구조

Android 레이아웃 코드

응용 프로그램은 다음 코드를 통해 layout_linear.xml 콘텐츠를 로드하는 MainActivity로 실행됩니다.

package com.journaldev.layouts;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


    Button back,next;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_linear);
        back=(Button)findViewById(R.id.back_button);
        next=(Button)findViewById(R.id.next_button);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,SecondActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

}

SecondActivityThirdActivity는 아래와 같이 각각 layout_relative.xmllayout_mixed.xml 레이아웃을 로드합니다.

package com.journaldev.layouts;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SecondActivity extends Activity {
    Button back,next;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_relative);
        back=(Button)findViewById(R.id.backbutton);
        next=(Button)findViewById(R.id.next);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(SecondActivity.this,ThirdActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(SecondActivity.this,MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

    }
}
package com.journaldev.layouts;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ThirdActivity extends Activity {
    Button back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_mixed);
        back=(Button)findViewById(R.id.back_button_pressed);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ThirdActivity.this,SecondActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

    }
}

Android LinearLayout RelativeLayout 예제 프로젝트 다운로드

참조: API 문서