본문 바로가기
프로그램 개발/안드로이드 스튜디오 개발

안드로이드 스튜디오 레이아웃 1(리니어 레이아웃)

by minchel1128 2021. 6. 12.

안드로이드에서는 버튼, 텍스트뷰, 에디트 텍스트 등의 위젯은 레이아웃이라는 틀 위에 존재하고 이를 배치할 수 있도록 설계가 되어있습니다.

레이아웃은 내부에 무엇을 담는 용도로 사용되며 가장 많이 사용되는 것은 이전 예시들에서도 사용하였다시피 리니어 레이아웃으로 선형 레이아웃이라고도 부릅니다.

레이아웃에서는 다음과 같은 속성이 자주 사용합니다.

  • orientation : 레이아웃 안에 배치할 위젯의 수직 또는 수평 방향을 설정한다.
  • gravity : 배치할 위젯의 정렬 방향을 좌측, 우측, 중앙 등으로 설정한다.
  • padding : 배치할 위젯의 여백을 설정한다.
  • layout_weight : 공간의 가중값을 설정하는데 여러 개의 레이아웃이 중복될 때 사용한다.
  • baselineAligned : 배치할 위젯을 보기 좋게 정렬한다.

주로 사용하는 레이아웃의 종류로는 리니어 레이아웃, 렐러티브 레이아웃, 프레임 레이아웃, 테이블 레이아웃, 그리드 레이아웃 등이 있습니다. 절대 좌표값을 지정하는 앱설루트 레이아웃도 있지만 안드로이드 휴대폰 및 태블릿마다 해상도가 다르기 때문에 사용상 문제가 발생하기 쉬워 오래된 프로그램이 아닌 이상 사용하지 않습니다.

  • 리니어 레이아웃은 선형 레이아웃으로 왼쪽 위부터 아래쪽으로 혹은 오른쪽으로 차례로 배치합니다.
  • 렐러티브 레이아웃은 상대 레이아웃으로 위젯 자신이 속한 레이아웃의 상하좌우 위치를 지정하여 배치하거나 다른 위젯으로부터 상대적인 위치를 지정합니다.
  • 테이블 레이아웃은 위젯을 행과 열의 개수를 지정한 테이블 형태로 배열합니다.
  • 그리드 레이아웃은 행 또는 열을 확장하여 다양하게 배치합니다.
  • 프레임 레이아웃은 위젯을 왼쪽 위에 일률적으로 겹쳐서 배치하여 중복되어 보이는 효과를 내며 상황에 따라 필요한 위젯을 보이는 방식에 주로 사용합니다.

1. 리니어 레이아웃

리니어 레이아웃은 대부분의 레이아웃 형태를 구성할 수 있어 사용도가 가장 높고 속성의 경우에는 다른 레이아웃에 공통적으로 적용되는 부분이 많습니다.

리니어 레이아웃에는 여러 속성이 있습니다.

orientation 속성은 값으로 vertical과 horizontal을 가지며 vertical은 위젯의 배치를 위에서 수직방향으로 배치하겠다는 의미이고 horizontal은 수평방향으로 배치하겠다는 의미입니다.

gravity와 layout_gravity 속성은 레이아웃 안의 위젯을 어디에 배치할 것인지를 결정하며 값으로 left, right, center, top, bottom 등을 가집니다. 이들은 2개를 조합하여 사용 가능한데 right|bottom와 같이 사용이 가능합니다.

layout_gravity의 경우에는 부모를 기준으로 자신의 부모의 오른쪽이나 중앙, 왼쪽 등에 배치한다는 의미로 사용합니다. 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CheckBox"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton"/>
        <Switch
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Switch"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CheckBox"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton"/>
        <Switch
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Switch"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:orientation="vertical"
        android:gravity="right|bottom">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CheckBox"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton"/>
        <Switch
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Switch"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:text="오른쪽"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="중앙"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:text="왼쪽"/>
    </LinearLayout>

</LinearLayout>

실행결과

값으로 올 수 있는 것으로는 위에서 추가적으로 center_vertical, center_horizontal, fill, fill_vertical, fill_horizontal, clip_vertical, clip_horizontal, start, end 등도 들어갈 수 있습니다.

baselineAligned 속성은 위젯을 보기 좋게 정렬한다는 의미로 사용하며 true와 false의 값을 가집니다. 다만 딱히 큰 차이라 없고 디폴트 값은 true이므로 생략해도 되어 크게 신경 쓰지 않아도 됩니다.

직접 풀어보기 5-1 부분은 다음과 같습니다.

조건으로는 리니어 레이아웃의 orientation은 vertical로 하고 버튼 3개를 생성하고 버튼의 layout_width는 110dp로 layout_height는 100dp로 한다는 조건입니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="110dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="버튼 1"/>
    <Button
        android:layout_width="110dp"
        android:layout_height="100dp"
        android:layout_gravity="left"
        android:gravity="left"
        android:text="버튼 2"/>
    <Button
        android:layout_width="110dp"
        android:layout_height="100dp"
        android:layout_gravity="right"
        android:gravity="right"
        android:text="버튼 3"/>

</LinearLayout>

중복 리니어 레이아웃

리니어 레이아웃은 중복으로 선언이 가능합니다.

즉 리니어 레이아웃 안에 리니어 레이아웃을 놓을 수 있으며 병렬로도 배치가 가능하다는 것입니다. 여기서 중요하게 작동하는 속성이 layout_weight 속성입니다.

layout_weight는 가중치 속성으로 부모 레이아웃을 기준으로 안에 들어있는 레이아웃의 높이 값 혹은 좌우 값을 설정하는 데 사용합니다.

코드부

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="버튼 1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="버튼 2"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#00FF00"
        android:gravity="center"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="버튼 3"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="벼튼 4"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#0000FF"
        android:gravity="center"
        android:orientation="vertical">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="버튼 5"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="버튼 6"/>
    </LinearLayout>
</LinearLayout>

실행결과

3개의 레이아웃을 1:1:1로 배치하고 싶다면 layout_weight의 값을 모두 1로 두면 되고 다르게 지정하고 싶다면 layout_height 속성을 0dp로 설정한 다음 layout_weight를 원하는 비율로 지정하면 됩니다.

직접 풀어보기 5-2의 코드 부분은 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#FF0000"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="#FFFF00"/>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="#000000"/>
        </LinearLayout>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#0000FF"/>

</LinearLayout>

실행결과

xml파일 말고 Java 코드만으로도 레이아웃을 형성할 수 있습니다. 다만 자주 사용하는 방법은 아니지만 화면을 직접 구성해야 하는 경우 적용할 수 있습니다.

자바 코드이고 xml파일은 없습니다.

package com.example.ch5_project5_1;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);

        LinearLayout baseLayout = new LinearLayout(this);
        baseLayout.setOrientation(LinearLayout.VERTICAL);
        baseLayout.setBackgroundColor(Color.rgb(0,255,0));
        setContentView(baseLayout,params);

        Button btn = new Button(this);
        btn.setText("버튼입니다.");
        btn.setBackgroundColor(Color.MAGENTA);
        baseLayout.addView(btn);

        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"코드로 생성한 버튼입니다.",Toast.LENGTH_LONG).show();
            }
        });
    }
}

실행결과

리니어 레이아웃 이외의 다른 레이아웃은 다음 게시글로 진행하겠습니다.

728x90
반응형