[Android] Getting Started (1)

Android developer site study

  • Getting Started
    • Building Your First App
    • Supporting Different Devices
    • Building a Dynamic UI with Fragments
    • Saving Data
    • Interacting with Other Apps
    • Working with System Permissions
https://developer.android.com/training/index.html

Android Project 생성

파일구조

app > java > com.example.myfirstapp > MainActivity.java

Activity에 대한 Class 정의. App 실행 시 Activity가 실행되며 내용을 표시하는 레이아웃 파일을 로드함.

app > res > layout > activity_main.xml

Activity의 레이아웃을 정의하는 XML 파일.

app > manifest > AndroidManifest.xml

App의 기본 특징을 설명하고 App의 각 구성요소를 정의함.

Gradle Scripts > build.gradle

Android Studio는 Build tool로 Gradle를 사용함. 프로젝트의 각 모듈을 위한 build.gradle 파일이 있고 전체 프로젝트를 위한 build.gradle 파일도 있음.
일반적으로는 모듈용 build.gradle 파일만 보면 된다.

App 실행

App을 실행하여 확인하는 방법엔 두 가지가 있음.

  1. 실제 기기에서 실행하는 방법
  2. 에뮬레이터에서 실행하는 방법

실제 기기에서 실행하는 방법

  1. 각 OEM 별 Driver를 [여기에서 다운로드] 받음.
  2. 디바이스에서 Settings > Developer options로 이동하여 USB debugging을 활성화 시킴. (Android 4.2 이상 버전에서는 Developer options가 숨겨져 있으므로 Settings > About phone의 Build number를 7번 누른 후 이전 화면으로 돌아가면 Developer options에 진입할 수 있음.)
  3. Android Studio에서 Run을 선택하여 실행.

에뮬레이터에서 실행하는 방법

AMD 칩셋에서는 하드웨어 가속화를 사용할 수 없기 때문에 에뮬레이터가 구동되지 않는다. (방법은 있지만 Intel 칩셋보다 10배 이상 느리므로 실제 기기에서 실행하는 방법이 추천되고 있다.)

[[AVD (Android Virtual Device)]]의 정의

  1. Tools > Android > AVD Manager
  2. Create Virtual Device
  3. 휴대폰 기기 선택 (ex. Nexus 6) > Next
  4. 원하는 시스템 이미지 선택 후 Next (특정 시스템 이미지가 설치되어 있지 않은 경우 download 링크를 선택하여 설치)
  5. 구성 설정 후 Finish

App 실행

  1. Android Studio에서 Run을 선택하여 실행.
  2. 생성한 에뮬레이터를 선택한 후 OK

간단한 사용자 인터페이스 구축

간단하게 Text field와 Button이 포함된 XML layout을 만들어 보자.

Android app의 GUI는 View 또는 ViewGroup개체의 계층 구조를 활용해 만들어진다.

View개체는 일반적으로 Button, TextField와 같은 UI Widget을 의미하고,

ViewGroup개체는 Grid, List 등의 하위 View의 layout을 정의하는 보이지 않는 View Container이다.

LayoutViewGroup의 서브클래스이다.

LinearLayout 생성

  1. app > res > layout > activity_main.xml 을 연다.
  2. 모든 내용을 삭제 후 아래 소스로 대체한다.
    1
    2
    3
    4
    5
    6
    7
    8
    <?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="horizontal">
    </LinearLayout>

LinearLayoutandroid:orientation 특성에 지정된 대로 하위 View를 세로 또는 가로 방향으로 배치하는 ViewGroup이다.

각 하위 View는 XML에 나열된 순서에 따라 화면에 표시된다.

Text field 추가

아래 EditText를 추가해본다.

1
2
3
4
5
6
7
8
9
10
11
<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="horizontal">
<EditText android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
</LinearLayout>

android:id

코드에서 객체를 참조할 때 사용하는 View의 고유 식별자.

XML에서 리소스 객체를 참조할 때에는 @ 기호를 사용해야 한다. @ 기호 다음에는 리소스 유형(여기서는 id), 슬래시(/), 리소스 이름(edit_message) 순서로 지정한다.

리소스 ID를 맨 처음으로 지정할 때에는 맨 앞에 + 를 붙여야 한다.

App Compile 시 SDK Tool은 프로젝트의 R.java 파일에서 ID 이름을 사용하여 새 리소스 ID를 생성한다.

android:layout_width, android:layout_height

너비와 높이에 대해 특정 크기를 사용할 수도 있으며 wrap_content, match_parent를 사용할 수 있다.

android:hint

Text field가 공백일 때 표시되는 기본 문자열이다.

리소스 객체는 비트맵, 레이아웃 파일, 문자열 등과 같이 앱 리소스와 연관된 고유한 정수 이름이다.
모든 리소스마다 해당 리소스 객체가 프로젝트의 R.java 파일에 정의되어 있다.
SDK Tool은 App을 Compile할 때마다 R.java 파일을 생성한다. 이 파일은 절대 직접 수정해서는 안 된다.

리소스 객체

문자열 리소스 추가

res > values > strings.xml 에 문자열 리소스 파일을 포함한다. 새로운 문자열 추가는 아래와 같이 하면 된다.

  1. res > values > strings.xml 을 연다.
  2. 아래와 같이 문자열을 추가한다.
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
</resources>

문자열 지정 시 항상 각 문자열을 리소스로 지정하는 것이 좋다. 문자열 리소스를 사용하면 한 위치에서 모든 UI 텍스트를 관리할 수 있기 때문에 텍스트를 손쉽게 찾고 업데이트 할 수 있다.

또한, 문자열 외현화(Externalization)을 통해 각 문자열 리소스에 대한 대체 정의를 제공하여 다양한 언어로 현지화할 수 있다.

Button 추가

activity_main.xml 에 아래와 같이 Button을 추가한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
</LinearLayout>

입력란을 화면 너비만큼 채우도록 설정

activity_main.xml 에서 \를 아래와 같이 수정한다.

1
2
3
4
5
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />

width를 0으로 설정하면 레이아웃 성능이 개선된다. 왜냐하면 wrap_content를 width로 사용하면 시스템으로 하여금 관련 없는 width를 산출하게 만들이 때문이다.
이런 동작을 하는 이유는 가중치(weight) 값이 남은 공간을 채우는 데 필요한 너비를 산출하게 만들기 때문이다.

완성된 activity_main.xml 레이아웃 파일은 아래와 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
</LinearLayout>

다른 액티비티 시작하기

사용자가 Send Button을 눌렀을 때 새로운 Activity를 시작하는 코드를 만들어보자.

Send Button에 응답하기

  1. res > layout > activity_main.xml의 Buttonandroid:onClick 특성을 추가한다.

이 특성은 사용자가 Send Button을 클릭할 때마다 시스템이 Activity에서 sendMessage() 메서드를 호출하도록 지시한다.

1
2
3
4
5
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
  1. java > com.example.myfirstapp > MainActivity.java에 sendMessage() 메서드 스텁을 추가

시스템이 이 메서드를 android:onClick에 지정된 메서드 이름과 일치시키도록 하려면 서명이 표시된 것과 정확히 같아야 한다. 이 메서드에는 다음과 같은 조건이 필요하다.

  • public method여야 한다.
  • 유효한 return값을 가져야 한다.
  • View가 유일한 매개변수(클릭한 View)여야 한다.
1
2
3
4
5
6
7
8
9
10
11
12
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
}

Intent 만들기

Intent는 별도의 구성요소 (ex. 두 개의 Activity) 간 Runtime Binding을 제공하는 객체이다. Intent는 App의 “작업 의도”를 나타내며 다양한 작업에 사용할 수 있다.
여기서는 Intent를 사용하여 다른 Activity를 시작해 보자.

MainActivity.java의 sendMessage()에 아래 코드를 추가한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}

Intent 생성자는 두 개의 매개변수를 가진다.

  • 첫 번째 매개변수 Context(Activity Class가 Context의 서브클래스이기 때문에 this를 사용함)
  • 시스템이 Intent를 전달할 App 구성요소의 Class (여기서는 시작할 Activity의 Class)

putExtra() 메서드는 EditText의 값을 Intent에 추가한다. Intent는 Key-value 쌍을 사용하는 Extra라는 Data type을 전달할 수 있다. 다음 Activity가 Key를 사용하여 Text value를 검색하기 때문에 Key는 public 상수인 EXTRA_MESSAGE이다. App package의 이름을 접두사로 사용해 Intent extra의 key를 정의하는 것이 좋다. 그렇게 하면 다른 App와 상호작용 시 Key를 고유하게 유지할 수 있다.

startActivity()는 Intent로 지정한 DisplayMessageActivity의 Instance를 시작한다.

이제 Class를 생성할 차례가 되었다.

두 번째 Activity 생성

  1. Project 창에서 app 폴더를 우클릭 후 New > Activity > Empty Activity를 선택
  2. Configure Activity 창에서 Activity Name에 “DisplayMessageActivity”를 입력 후 Finish

Android Studio는 아래 세 가지 작업을 자동으로 수행하게 된다.

  • 필수 onCreate() 메서드의 구현을 통해 Class DisplayMessageActivity.java 를 생성한다.
  • 해당 레이아웃 파일 activity_display_message.xml을 생성한다.
  • 필수 요소를 AndroidManifest.xml에 추가한다.

메시지 표시하기

DisplayMessageActivity.java 에서 아래 코드를 onCreate() 에 추가한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}

위의 소스에 대해 설명은 아래와 같다.

  1. getIntent()를 호출하면 Activity를 시작한 Intent를 가져온다. 모든 Activity는 사용자의 탐색 방식과 상관없이 Intent에 의해 호출된다.
  2. getStringExtra()를 호출하면 첫 번째 Activity에서 Data를 검색한다.
  3. TextView를 생성하고 Size와 Message를 설정한다.
  • 참고
    이전 버전의 Android Studio로 생성한 XML 레이아웃에는 android.id 특성이 포함되지 않을 수도 있다.
    레이아웃에 android:id 특성이 없으면 findViewById()를 호출할 수 없기 때문에 이런 경우 xml 파일을 열고 android:id 특성을 추가해주어야 한다.

즉, activity_display_message.xml 파일은 아래처럼 구성되어야 한다.

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.example.myfirstapp.DisplayMessageActivity"
android:id="@+id/activity_display_message"
>
</android.support.constraint.ConstraintLayout>

출처

Share