춤추는 개발자

[Android Studio] 기본 지식 배우기 - 2 본문

Android/study_til

[Android Studio] 기본 지식 배우기 - 2

Heon_9u 2020. 11. 26. 22:41
728x90
반응형

1. 사용자 인터페이스 이해하기

UI는 사용자와 상호작용할 수 있는 Activity에서 이루어지며 이를 작성하는 방법은 3가지가 있다.

xml파일로만 화면 구성하기, 코드로 UI구성하기, 코드와 xml파일을 함께 사용하기.

 

첫번째 포스팅에서 xml파일로만 화면을 구성하는 방법을 배웠다. 이번에는 java코드로 화면 구성한다면 다음과 같이 사용할 수 있다.

 

package com.example.mywork00;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        TextView t1 = new TextView(this);
        t1.setTextSize(30);
        t1.setText("코드로 화면 구성");
        layout.addView(t1);

        ImageView i1 = new ImageView(this);
        i1.setImageResource(R.drawable.bts);
        layout.addView(i1);
        setContentView(layout);
    }
}

 

onCreate메소드는 안드로이드 운영체제 시스템에 의해서 Activity가 실행될 때, 가장 먼저 실행되는 메소드다. 보통 이곳에 findViewById메소드, 버튼 리스너등을 넣는다.

 

Activity의 메소드인 setContentView는 파라미터를 화면에 나타나게 한다. 처음에는 R.layout.activity_xml파일이 파라미터로 주어지지만 위처럼 java코드로 구성한 layout을 파라미터로 넘길 수 있다. 하지만 모든 UI를 이런 방법으로 처리하기에는 힘들 수 있다.

 

 위 코드의 결과는 다음과 같다.

 이제 코드와 xml을 함께 사용하기위해 xml에서 작성한 뷰들에 고유 식별자(id)를 기입할 것이다.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/t1"/>

</LinearLayout>

 

이제 xml파일에 있는 TextView를 java코드에서 findViewById를 이용해 호출하고 이를 변경해보겠다.

 

package com.example.mywork00;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

        TextView t1 = (TextView) findViewById(R.id.t1);
        t1.setTextSize(30);
        t1.setText("Success");
    }
}

 

이제 Project를 실행하면 다음과 같은 결과가 나온다.

 

 

아래 표는 xml파일에서 사용되는 속성과 관련된 코드에서 사용되는 메소드들이다.

 

xml속성 xml속성과 관련된 메소드 역할
text setText 표시되는 텍스트를 설정
textSize setTextSize 텍스트의 크기를 설정
textColor setTextColor 텍스트 색을 설정
textStyle setTypeface 텍스트를 bold, italic, bolditalic으로 설정
background setBackgroundColor 배경색을 설정
rotation setRotation 회전한다
visibility setVisibility 화면에 나타나거나 감춘다

 

2. 레이아웃

 레이아웃은 뷰들을 담는 그룹으로 자주 사용되는 레이아웃의 종류는 LinearLayout, RelativeLayout, FrameLayout이 있다. 이 중, LinearLayout을 가장 많이 사용한다.

 

앞에서 LinearLayout의 속성 중 android:orientation으로 뷰들을 수직, 수평으로 정렬하는 방법을 배웠다. 이를 응용해서 6개의 버튼을 2x3배열로 정렬한다면 다음과 같다.

 

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

    <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="button1"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button2"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button3"/>

    </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="button4"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button5"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button6"/>

    </LinearLayout>
</LinearLayout>

 

역시나 결과는 다음과 같다.

2-1. padding

이제, 각 Button마다 paddinglayout_margin을 적용해보겠다. padding이란 입력하는 속성값이 커질수록 Button이 커지고 여백이 넓어지게 된다.

 

2-2. layout_margin

뷰의 바깥부분, 상하좌우에 여백을 주는 속성으로 layout_margin이라고 한다.

 

2-3.layout_width, layout_height

둘은 뷰의 크기를 결정하는 속성이다.

 

속성값 역할
fill_parent (=match_parent) 크기를 꽉 채운다.
wrap_content 뷰(텍스트 크기, 이미지 크기) 내용물의 크기에 맞추고, 내용물의 크기에 맞추어 가로, 세로 크기가 결정된다.

 

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="button"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:text="button"/>

 

두 속성값 대신, 크기를 나타내는 단위로 dp와 px이 있습니다.

 

속성값 역할
dp 디바이스 크기에 상관없이 일정한 비율을 유지할 수 있어서 많이 사용되는 단위
px px는 화면 위의 점으로 디바이스의 DPI가 높으면 1인치당 들어갈 수 있는 점의 수가 많아져서 이미지가 작아지게 된다. 디바이스마다 크기가 다르기 때문에 권장하지 않는다.

 

2-4. RelativeLayout

뷰 간의 관계를 정의하여 뷰의 위치를 상대적 레이아웃에 대해서 살펴본다. 이미 존재하는 뷰를 대상으로 새로운 뷰의 위치를 정하기 때문에 이미 존재하는 뷰에 대한 id값이 필요하다. 아래 표는 RelativeLayout에서 사용되는 속성들이다.

 

속성 설명
layout_above 기준 뷰의 위에 배치
layout_below 기준 뷰의 아래에 배치
layout_toLeftOf 기준 뷰의 왼쪽에 배치
layout_toRightOf 기준 뷰의 오른쪽에 배치
layout_alignTop 기준 뷰의 상단 가장자리에 맞춰 배치
layout_alignBottom 기준 뷰의 하단 가장자리에 맞춰 배치
layout_alignLeft 기준 뷰의 왼쪽 가장자리에 맞춰 배치
layout_alignRight 기준 뷰의 오른쪽 가장자리에 맞춰 배치

 

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

    <Button
        android:id="@+id/b1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button"/>

    <Button
        android:id="@+id/b2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/b1"
        android:text="button"/>

    <Button
        android:id="@+id/b3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/b2"
        android:text="button"/>

</RelativeLayout>

 

2-5. FrameLayout

FrameLayout은 왼쪽 상단을 기준으로 뷰들을 겹쳐서 쌓아놓는 레이아웃이다. 이미지 3개를 만들고 FrameLayout안에 넣으면 다음과 같다.

 

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    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="fill_parent"
    android:layout_height="fill_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/bts"/>

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/bts"/>

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/bts"/>

</FrameLayout>

 

2-6. TableLayout

각 뷰들을 열과 행을 갖는 테이블 형식으로 배치할 수 있다. <TableRow> ... </TableRow>의 개수가 행의 개수, TableRow안에 있는 뷰의 개수가 열의 개수가 된다. 간단한 계산기화면을 TableLayout으로 나타내면 다음과 같다.

 

2-7. ConstraintLayout

개발자가 쉽게 UI를 설계하도록 돕는 레이아웃으로 RelativeLayout과 비슷하다. 가장 큰 장점은 Infer Constraints기능을 통해 레이아웃에 배치된 뷰들을 쉽게 관계를 지정할 수 있다.

 

Button의 모서리에 있는 ○는 다른 뷰와의 정렬, 꼭지점에 있는 ■는 뷰의 크기를 조정한다.

 

2-8. ConstraintLayout 응용하기.

이를 이용해 간단히 사진과 글을 보여주는 앱을 제작해보겠습니다.

 

ConstraintLayout을 완성하고 실행하기 전, 반드시 Infer Constraint를 클릭하여 뷰의 현재 상태를 기반으로 관계를 설정해야 한다. 그렇지 않으면 뷰들이 겹쳐서 정렬상태가 엉망이 되버린다.

 

 

여기까지 두번째 포스팅 마무리하겠습니다. 내일까지 기본적인 부분을 다루고 주말이나 다음주부터 DB를 활용한 영어단어 앱을 만들어 볼 예정입니다. 130page이상의 분량이라 2~3일 계획하고 진행해보겠습니다.

728x90
반응형