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

안드로이드 스튜디오 레이아웃 2 (기타 레이아웃)

by minchel1128 2021. 6. 21.

이전 게시글에서 이어져 옵니다.

레이아웃에는 리니어 레이아웃이 주로 사용되지만 렐러티브 레이아웃, 프레임 레이아웃, 테이블 레이아웃, 그리드 레이아웃이 도 있습니다.

1. 렐러티브 레이아웃

렐러티브 레이아웃은 상대 레이아웃이라고도 하며 내부에 포함된 위젯을 상대적인 위치로 배치합니다.

렐러티브 레이아웃의 속성 중에는 부모의 어느 위치에 배치할지 결정하는 속성이 있는데 모두 7가지입니다.

  • layout_ alignParentLeft : 부모 레이아웃의 왼쪽 위
  • layout_centerHorizontal : 부모 레이아웃의 중앙 위
  • layout_alignParentRight : 부모 레이아웃의 오른쪽 위
  • layout_alignParentTop : 부모 레이아웃의 상단
  • layout_centerVertical : 부모 레이아웃의 중간
  • layout_alignParentBottom : 부모 레이아웃의 하단
  • layout_centerParent : 부모 레이아웃의 중앙

또한 각 속성 값은 true와 false를 가집니다.

예시 코드

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="위쪽"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:text="좌측"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="중앙"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="우측"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="아래"/>

</RelativeLayout>

예시 이미지

또한 다른 위치에 배치할 때는 더 다양한 속성을 사용하게 되는데 다음과 같습니다. 모두 앞에 layout_이 붙습니다.

  • toLeftOfalignTop : 왼쪽 위
  • toLeftOfalignBaseline : 왼쪽 중앙
  • toLeftOfalignBottom : 왼쪽 아래
  • abovealignLeft : 위 왼쪽
  • above : 위 중앙
  • abovealignRight : 위 오른쪽
  • toRightOfalignTop : 오른쪽 위
  • toRightOfalignBaseline : 오른쪽 중앙
  • toRightOfalignBottom : 오른쪽 아래
  • belowalignLeft : 아래 왼쪽
  • belowalignRight : 아래 오른쪽

예시 코드

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="150dp"
        android:layout_height="150dp"
        android:id="@+id/baseBtn"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="기준 위젯"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/baseBtn"
        android:layout_toLeftOf="@id/baseBtn"
        android:text="1번" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/baseBtn"
        android:layout_toLeftOf="@id/baseBtn"
        android:text="2번" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/baseBtn"
        android:layout_toLeftOf="@id/baseBtn"
        android:text="3번" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/baseBtn"
        android:layout_alignLeft="@id/baseBtn"
        android:text="4번"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@id/baseBtn"
        android:layout_below="@id/baseBtn"
        android:text="5번"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/baseBtn"
        android:layout_toRightOf="@id/baseBtn"
        android:text="6번"/>
        
</RelativeLayout>

예시 이미지

예시 코드

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/baseBtn1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="기준1"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/baseBtn2"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="기준2"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/baseBtn2"
        android:text="1번"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@id/baseBtn1"
        android:text="2번"/>

</RelativeLayout>

예시 이미지

테이블 레이아웃

테이블 레이아웃은 주로 위젯을 표 형태로 배치할 때 사용하며 테이블 레이아웃을 사용해 행과 열의 수를 정한 뒤에 위젯을 배치하는 형태로 사용합니다.

테이블 레이아웃은 <TableRow>와 함께 사용되며 <TableRow>의 수가 행의 수입니다. 그리고 열의 수는 <TableRow> 안에 포함된 위젯의 수로 결정됩니다.

속성으로는 다음과 같습니다.

  • layout_span : 열을 합쳐서 표시
  • layout_column : 지정된 열에 현재 위젯을 표시
  • stretchColumns : 지정된 열의 폭을 늘리라는 의미

열의 번호는 0번부터 시작합니다.

예시 코드

<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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"
    tools:context=".MainActivity">

    <TableRow>
        <Button
            android:text="1"/>
        <Button
            android:layout_span="2"
            android:text="2"/>
        <Button
            android:text="3"/>
    </TableRow>
    <TableRow>
        <Button
            android:layout_column="1"
            android:text="4"/>
        <Button
            android:text="5"/>
        <Button
            android:text="6"/>
    </TableRow>

</TableLayout>

예시 이미지

실습 코드

xml코드

<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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"
    tools:context=".MainActivity">

    <TableRow>
        <EditText
            android:id="@+id/Edit1"
            android:layout_span="5"
            android:hint="숫자 1 입력"/>
    </TableRow>
    <TableRow>
        <EditText
            android:id="@+id/Edit2"
            android:layout_span="5"
            android:hint="숫자 2 입력"/>
    </TableRow>
    <TableRow>
        <Button
            android:id="@+id/BtnNum0"
            android:text="0"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/BtnNum1"
            android:text="1"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/BtnNum2"
            android:text="2"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/BtnNum3"
            android:text="3"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/BtnNum4"
            android:text="4"
            android:layout_weight="1"/>
    </TableRow>
    <TableRow>
        <Button
            android:id="@+id/BtnNum5"
            android:text="5"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/BtnNum6"
            android:text="6"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/BtnNum7"
            android:text="7"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/BtnNum8"
            android:text="8"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/BtnNum9"
            android:text="9"
            android:layout_weight="1"/>
    </TableRow>
    <TableRow>
        <Button
            android:id="@+id/BtnAdd"
            android:layout_margin="5dp"
            android:layout_span="5"
            android:text="더하기"
            android:layout_weight="1"/>
    </TableRow>
    <TableRow>
        <Button
            android:id="@+id/BtnSub"
            android:layout_margin="5dp"
            android:layout_span="5"
            android:text="빼기"
            android:layout_weight="1"/>
    </TableRow>
    <TableRow>
        <Button
            android:id="@+id/BtnMul"
            android:layout_margin="5dp"
            android:layout_span="5"
            android:text="곱하기"
            android:layout_weight="1"/>
    </TableRow>

    <TableRow>
        <Button
            android:id="@+id/Btndiv"
            android:layout_margin="5dp"
            android:layout_span="5"
            android:text="나누기"
            android:layout_weight="1"/>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/TextResult"
            android:layout_margin="5dp"
            android:layout_span="5"
            android:text="계산결과 : "
            android:textColor="#FF0000"
            android:textSize="20dp"
            android:layout_weight="1"/>
    </TableRow>

</TableLayout>

Java코드

package com.example.ch5_project5_2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText edit1, edit2;
    Button btnAdd, btnSub, btnMul, btnDiv;
    TextView textResult;
    String num1, num2;
    Integer result;
    Button[] numButtons = new Button[10];
    Integer[] numBtnIDs={R.id.BtnNum0,R.id.BtnNum1,R.id.BtnNum2,R.id.BtnNum3,R.id.BtnNum4,R.id.BtnNum5,R.id.BtnNum6,R.id.BtnNum7,R.id.BtnNum8,R.id.BtnNum9};
    int i;

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

        setTitle("테이블 레이아웃 계산기");

        edit1 = (EditText) findViewById(R.id.Edit1);
        edit2 = (EditText) findViewById(R.id.Edit2);
        btnAdd = (Button) findViewById(R.id.BtnAdd);
        btnSub = (Button) findViewById(R.id.BtnSub);
        btnMul = (Button) findViewById(R.id.BtnMul);
        btnDiv = (Button) findViewById(R.id.Btndiv);
        textResult = (TextView) findViewById(R.id.TextResult);

        btnAdd.setOnTouchListener(new View.OnTouchListener(){
            public boolean onTouch(View arg0, MotionEvent arg1){
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
                result = Integer.parseInt(num1)+Integer.parseInt(num2);
                textResult.setText("계산결과 : "+result.toString());
                return false;
            }
        });
        btnSub.setOnTouchListener(new View.OnTouchListener(){
            public boolean onTouch(View arg0, MotionEvent arg1){
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
                result = Integer.parseInt(num1)-Integer.parseInt(num2);
                textResult.setText("계산결과 : "+result.toString());
                return false;
            }
        });
        btnMul.setOnTouchListener(new View.OnTouchListener(){
            public boolean onTouch(View arg0, MotionEvent arg1){
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
                result = Integer.parseInt(num1)*Integer.parseInt(num2);
                textResult.setText("계산결과 : "+result.toString());
                return false;
            }
        });
        btnDiv.setOnTouchListener(new View.OnTouchListener(){
            public boolean onTouch(View arg0, MotionEvent arg1){
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
                result = Integer.parseInt(num1)/Integer.parseInt(num2);
                textResult.setText("계산결과 : "+result.toString());
                return false;
            }
        });

        for(i=0;i< numBtnIDs.length;i++){
            numButtons[i]=(Button)findViewById(numBtnIDs[i]);
        }
        for(i=0;i<numBtnIDs.length;i++){
            final int index;
            index = i;

            numButtons[index].setOnClickListener(new View.OnClickListener(){
                public void onClick(View v){
                    if(edit1.isFocused()==true){
                        num1 = edit1.getText().toString()+numButtons[index].getText().toString();
                        edit1.setText(num1);
                    } else if(edit2.isFocused()==true){
                        num2 = edit2.getText().toString()+numButtons[index].getText().toString();
                        edit2.setText(num2);
                    } else{
                        Toast.makeText(getApplicationContext(),"먼저 에디트텍스트를 선택하세요",Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    }
}

실습 이미지

실행결과

유튜브 링크

https://youtu.be/byzKeb_dmE8

카카오 영상

그리드 레이아웃

그리드 레이아웃은 테이블 레이아웃처럼 위젯을 표 형태로 배치할 때 사용하지만 좀 더 직관적으로 배치할 수 있으며 행 확장도 간단하게 할 수 있어 유연한 화면 구성에 적합합니다.

그리드 레이아웃은 안드로이드 4.0 이상부터 지원됩니다.

그리드 레이아웃의 자주 사용되는 속성은 다음과 같습니다.

  • rowCount
  • columnCount
  • orientation
  • layout_row
  • layout_column
  • layout_rowSpan
  • layout_columnSpan
  • layout_gravity

예시 코드

<?xml version="1.0" encoding="utf-8"?>
<GridLayout 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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:columnCount="4"
    android:rowCount="2">

    <Button
        android:layout_column="0"
        android:layout_row="0"
        android:layout_rowSpan="2"
        android:layout_gravity="fill_vertical"
        android:text="1"/>
    <Button
        android:layout_column="1"
        android:layout_row="0"
        android:layout_columnSpan="2"
        android:layout_gravity="fill_horizontal"
        android:text="2"/>
    <Button
        android:layout_column="3"
        android:layout_row="0"
        android:text="3"/>
    <Button
        android:layout_column="1"
        android:layout_row="1"
        android:text="4"/>
    <Button
        android:layout_column="2"
        android:layout_row="1"
        android:text="5"/>
    <Button
        android:layout_column="3"
        android:layout_row="1"
        android:text="6"/>

</GridLayout>

예시 이미지

프레임 레이아웃은 단순히 레이아웃 내의 위젯을 왼쪽 상단부터 겹쳐서 출력해줍니다. 테이블 레이아웃은 그 자체를 사용하기보다는 탭 위젯 등과 혼용하는 형태로 사용됩니다.

속성으로는 다음과 같습니다.

  • foreground
  • foregroundGravity

예시 코드

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:foreground="@drawable/ic_launcher_foreground"
    android:foregroundGravity="fill_horizontal"
    tools:context=".MainActivity">
    <RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ratingBar1"/>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_background"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check Box"/>


</FrameLayout>

예시 이미지

다음 게시글에서는 고급 위젯 기능에 대해 진행하며 코틀린 관련 내용은 따로 진행하겠습니다.

728x90
반응형