• 검색 결과가 없습니다.

학습목표

N/A
N/A
Protected

Academic year: 2022

Share "학습목표"

Copied!
16
0
0

로드 중.... (전체 텍스트 보기)

전체 글

(1)

1 학습목표

❍ 안드로이드에서 메뉴를 작성하고 사용하는 방법을 배운다.

❍ 안드로이드에서 대화상자를 만들고 사용하는 방법을 배운다.

2 확인해 볼까?

우리가 사용하는 안드로이드 앱은 메뉴 버튼을 누르면 선택할 수 있는 메뉴가 나온 다. 그리고 사용자의 입력을 받거나 사용자에게 경고 메시지를 전달할때 대화상자를 출력하기도 한다. 이러한 기능은 어떻게 구현해야 할까?

3 메뉴

1) 학습하기

안드로이드의 메뉴는 옵션 메뉴(Option Menu)와 컨텍스트 메뉴(Context Menu) 두 가지가 있다. 옵션 메뉴는 키패트의 메뉴 버튼을 눌렀을 때 화면 하단 에 메뉴가 나온다. 컨텍스트 메뉴는 위젯을 롱클릭하면 나오는데, 일반적으로 제 목과 함께 화면의 중앙에 출력된다. 메뉴를 만드는 방법은 메뉴 XML 파일을 생 성한 후 Java 코드에서 호출하는 방법과 Java 코드로만 만드는 방법이 있다. 일반 적으로 많이 사용하는 방법인 메뉴 XML 파일을 이용한 방법에 대해 자세히 알 아보자.

(2)

<menu>

<item

android:id="@+id/항목ID"

android:title="항목제목"/>

</menu>

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.메뉴XML아이디, menu);

return true;

}

public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){

case R.id.메뉴항목ID;

return true;

}

[그림 8-1] XML을 이용한 옵션 메뉴 설정 방법

[그림 8-1]은 XML을 이용하여 옵션 메뉴를 만드는 순서를 보여주고 있다. 첫 순서인 메뉴 XML을 구성하는 방법은 다음과 같다.

두 번째 순서는 액티비티에서 onCreateOptionMenu() 메소드를 오버라이딩해야 한다. 이 메소드는 메뉴 버튼을 클릭하였을 때 호출된다.

마지막으로 액티비티에서 onOptionsItemSelected() 메소드를 오버라이딩해야 한 다. 이 메소드는 옵션 메뉴에서 메뉴 항목을 선택하였을 때 호출된다.

(3)

return false;

}

안드로이드 SDK 4.0.3 버전부터는 프로젝트 생성시 [res]-[menu]에 main.xml이 라는 메뉴가 자동으로 생성되어 있으며, 액티비티에도 onCreateOptionMenu() 메 소드는 자동으로 오버라이드 되어 있다. 따라서 자동으로 완성되어 있는 XML 메 뉴와 메소드를 활용하면서 옵션 메뉴를 작성한다면 onOptionsItemSelected() 메소 드만 액티비티에 오버라이드 해서 사용하면 된다. 다음의 활동하기 실습을 통해 옵션 메뉴의 사용법을 익혀보자.

2) 활동하기 ❍ 활동 개요

본 프로젝트에서는 옵션 메뉴를 이용하여 텍스트뷰의 글자색을 바꾸는 앱을 만 들어 본다.

❍ 활동 과정

(1) 새로운 안드로이드 프로젝트를 만들고 이름은 Menu로 한다. 프로젝트 생성 과정 은 2차시 ‘활동 과정: 안드로이드 응용 프로그램 작성해보기’의 (3)~(6)의 과정을 따른 다.

(2) 프로젝트의 [res]-[menu] 폴더가 있으면 (3)으로 넘어가고 없다면 다음과 같은 과 정으로 만들자. Package Explorer의 [Menu]-[res] 폴더에서 마우스 오른쪽 버튼을 클릭 하고 [New]-[Folder]를 선택한다. [New Folder] 창에서 Folder name에 “menu"을 입력 한 후 <Finish>를 클릭한다.

(3) 프로젝트의 [res]-[menu] 폴더에 main.xml이 있으면 (4)로 넘어가고 없다면 다음 과정을 통해 만들자. Package Explorer의 [Menu]-[res]-[menu] 폴더에서 마우스 오른쪽 버튼을 클릭하고 [New]-[File]를 선택한다. [File] 창에서 File name에 “main.xml"을 입 력한 후 <Finish>를 클릭한다.

(4)

[그림 8-2]메뉴 폴더 생성

[그림 8-3]메뉴 xml 파일 생성

(5)

[예제 8-1]main.xml (메뉴 폴더) 1

2 3 4 5 6 7 8 9 10 11 12 13

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item

android:id="@+id/itemRed"

android:title="빨강"/>

<item

android:id="@+id/itemGreen"

android:title="초록"/>

<item

android:id="@+id/itemBlue"

android:title="파랑"/>

</menu>

1, 13행 메뉴의 시작과 끝을 나타낸다.

3행 아이템의 시작을 나타낸다. 6행의 />으로 아이템의 끝을 표시한다.

4행 아이템의 아이디를 설정한다.

5행 아이템의 제목을 설정한다.

[예제 8-2]main.xml (레이아웃 폴더) 1

2 3 4 5 6 7 8 9

<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:gravity="center"

tools:context=".MenuActivity" >

<TextView

android:id="@+id/tvMenu"

(4) Package Explorer의 [Menu]-[res]-[menu]-[main.xml] 파일을 더블클릭해서 열고 아 래쪽의 [main.xml] 탭을 선택하여, 다음과 같이 코딩한다.

(5) Package Explorer에서 [Menu]-[res]-[layout]-[main.xml] 파일을 열고, [main.xml]

탭을 클릭하여 화면을 구성한다. 화면 구성은 다음과 같다.

. RelativeLayout을 LinearLayout으로 변경하고 gravity 속성을 center로 설정한다.

. TextView 하나로 화면을 구성하고 글씨 크기는 30dp로 설정한다.

(6)

10 11 12 13 14 15

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="메뉴 테스트"

android:textSize="30dp" />

</LinearLayout>

[예제 8-3]MenuActivity.java 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

package com.example.menu;

import android.app.Activity;

import android.graphics.Color;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.TextView;

public class MenuActivity extends Activity {

TextView tvMenu;

@Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.main);

setTitle("간단 메뉴");

tvMenu = (TextView) findViewById(R.id.tvMenu);

}

(6) Package Explorer의 [Menu]-[src]-[com.example.menu]-[MenuActivity.java] 파일을 더블클릭해서 열고 아래와 같이 코딩한다.

(7)

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub

switch (item.getItemId()) { case R.id.itemRed:

tvMenu.setTextColor(Color.RED);

return true;

case R.id.itemGreen:

tvMenu.setTextColor(Color.GREEN);

return true;

case R.id.itemBlue:

tvMenu.setTextColor(Color.BLUE);

return true;

}

return false;

} }

12, 20행 텍스트뷰 변수를 선언하고 위젯과 연결한다.

24~28행 메뉴가 클릭되었을 때의 동작을 구현한다. 안드로이드 SDK 4.0.3부터는 생성시 구현 되어 있다.

31행~45행 onOptionsItemSelected() 메소드를 오버라이드 하여 구현한다. 액티비티 안에서 마 우스 오른쪽 버튼을 클릭하여 [Source]- [Override/Implement Methods...]를 선택한다.

대화상자에서 onOptionsItemSelected() 메소드를 선택한 후 <OK>버튼을 눌러 메소드를 추 가한 후 코딩한다.

33행 선택된 메뉴 항목에 대한 아이디에 따라 수행해야 할 내용을 switch 문으로 분기한다.

(7) 프로젝트를 실행하여 결과를 확인한다. [그림 8-4]와 같이 동작할 것이다.

(8)

[그림 8-4] 간단 메뉴 실행 화면

4 대화상자

1) 학습하기

대화상자(Dialog)는 사용자에게 중요한 상황을 알리거나 또는 사용자에게 어떤 선택을 하게 하는 목적으로 사용된다. 대화상자의 일반적인 사용방법은 [그림 8-5]와 같다.

(9)

[그림 8-5] 대화 상자 사용 순서

AlertDialog.Builder 클래스로 대화상자를 생성한 다음, 다양한 메소드들을 사용 하여 대화상자를 꾸민다. 최종적으로 show() 메소드를 사용하여 대화상자를 화면 에 출력한다. 활동하기 실습을 통해 대화상자의 사용법을 익히도록 하자.

2) 활동하기 ❍ 활동 개요

이번 프로젝트에서는 대화상자를 통해 사용자의 이름과 이메일 주소를 입력받 고, 입력받은 사용자 정보를 메인 화면에 출력해주는 앱을 만들어 보자.

❍ 활동 과정

(1) 새로운 안드로이드 프로젝트를 만들고 이름은 Dialog로 한다. 프로젝트 생성 과정

(10)

[예제 8-4]main.xml 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

<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:gravity="center_horizontal"

android:orientation="vertical"

tools:context=".DialogActivity" >

<Button

android:id="@+id/btnInput"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="사용자 정보 입력하기" />

<TextView

android:id="@+id/tvName"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="사용자 이름: "

android:textSize="20dp" />

<TextView

android:id="@+id/tvAge"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="나이: "

android:textSize="20dp" />

<TextView

android:id="@+id/tvEmail"

은 2차시 ‘활동 과정: 안드로이드 응용 프로그램 작성해보기’의 (3)~(6)의 과정을 따른 다.

(2) Package Explorer에서 [Dialog]-[res]-[layout]-[main.xml] 파일을 열고, [main.xml] 탭 을 클릭하여 화면을 구성한다. 화면 구성은 다음과 같다.

. RelativeLayout을 LinearLayout으로 변경하고 orientation을 vertical로 gravity는 center_horizontal로 설정한다.

. Button과 TextView 3개로 구성한다.

(11)

27 28 29 30 31

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="이메일: "

android:textSize="20dp" />

</LinearLayout>

[예제 8-5]dialog.xml 1

2 3 4 5 6

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="10dp" >

(3) 대화상자의 XML 파일을 만든다. [res]-[layout]에서 마우스 오른쪽 버튼을 클 릭하고 [New]-[Other]를 선택한다. [Select a wizard] 창에서 [Android]- [Android XML Layout File]을 선택하고 <Next>를 클릭한다. [New Android Layout XML File] 창이 나오면 File에 "dialog.xml"을 입력하고, Root Element에서 LinearLayout을 선택한 후 <Finish>를 클릭한다.

[그림 8-6] dialog xml 파일 생성

(4) dialog.xml 파일을 코딩하여 대화상자를 다음과 같이 구성한다.

. 텍스트뷰, 에디트뷰, 텍스트뷰, 에디트뷰, 텍스트뷰, 에디트뷰로 구성한다.

(12)

[예제 8-6]DialogActivity.java 1

2 3 4 5

package com.example.dialog;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.DialogInterface;

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="사용자 이름" />

<EditText

android:id="@+id/dlgEdtName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="이름을 입력하세요." />

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="나이" />

<EditText

android:id="@+id/dlgEdtAge"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="나이를 입력하세요." />

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="이메일" />

<EditText

android:id="@+id/dlgEdtEmail"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="이메일을 입력하세요." />

</LinearLayout>

(5) 이클립스의 Package Explorer에서 [Dialog]-[src]-[com.example.dialog]- [DialogActivity.java] 파일을 연다. onCreateOptionsMenu() 메소드는 사용하지 않으므 로 관련 부분을 삭제한다.

(13)

6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

public class DialogActivity extends Activity {

TextView tvName, tvAge, tvEmail;

Button btnInput;

EditText dlgEdtName, dlgEdtAge, dlgEdtEmail;

View dialogView;

@Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.main);

setTitle("사용자 정보 입력");

tvName = (TextView) findViewById(R.id.tvName);

tvAge = (TextView) findViewById(R.id.tvAge);

tvEmail = (TextView) findViewById(R.id.tvEmail);

btnInput = (Button) findViewById(R.id.btnInput);

btnInput.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

dialogView = (View) View.inflate(DialogActivity.this, R.layout.dialog, null);

AlertDialog.Builder dlg = new AlertDialog.Builder(DialogActivity.this);

dlg.setTitle("사용자 정보 입력");

dlg.setIcon(R.drawable.ic_launcher);

dlg.setView(dialogView);

dlg.setPositiveButton("확인", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

dlgEdtName = (EditText) dialogView.findViewById(R.id.dlgEdtName);

dlgEdtAge = (EditText) dialogView .findViewById(R.id.dlgEdtAge);

dlgEdtEmail = (EditText) dialogView.findViewById(R.id.dlgEdtEmail);

(14)

46 47 48 49 50 51 52 53 54 55 56

tvName.setText("이름: " + dlgEdtName.getText().toString());

tvAge.setText("나이: " + dlgEdtAge.getText().toString());

tvEmail.setText("이메일" + dlgEdtEmail.getText().toString());

} });

dlg.setNegativeButton("취소", null);

dlg.show();

} });

} }

34~38행 dialog.xml 파일을 인플레이트해서 dialogView에 대입한 후 38행에서 setView()로 인플레이트한 뷰를 대화상자로 사용했다.

39~50행 <확인> 버튼에 대한 동작 코드이다. <확인> 버튼을 누르면 대화상자의 에디트텍스트 에 있는 내용이 액티비티의 텍스트뷰로 들어가게 된다.

(6) 프로젝트를 실행하여 결과를 확인한다. [그림 8-7]과 같이 동작할 것이다.

[그림 8-7] 실행 화면

5 배운 내용 정리

1) 안드로이드에서 옵션 메뉴는 다음과 같은 과정으로 사용할 수 있다.

(15)

2) 안드로이드에서 대화 상자는 다음과 같은 과정으로 사용할 수 있다.

6 학습 확인하기

1) 옵션 메뉴와 컨텍스트 메뉴는 언제 등장하는지 설명하라.

(16)

2) 다음의 옵션 메뉴에 대한 메소드에 대해 간단히 설명하라.

① onCreateOptionMenu()

② onOptionsItemSelected()

6 지식창고

❍ 참고문헌

[1] 우재남, 이복기, “안드로이드 프로그래밍”, 한빛미디어, 2012 [2] 김상형, “안드로이드 프로그래밍 정복”, 한빛미디어, 2011

❍ 참고사이트

[1]

http://developer.android.com/

[2]

http://developer.android.com/reference

참조

관련 문서

OnCreate() // WM_CREATE 메시지 핸들러 PreCreateWindow() // 윈도우 생성 옵션 지정. • WM_COMMAND

이러한 개념을 일반화시켜 서 특정 시간 t 에서의 기울기를 순시 주파수(instantaneous

• 옵션계약 (option contract)이란 일정한 기초자산(underlying asset)을 미리 정해진 가격(행사가격 : exercise price)으로 만 기일 또는 만기일 이전에 매입하거나

② 고구려어와 퉁구스어와의 관계 &gt; 신라어와 퉁구스어와의 관계 (고구려어는 퉁구스와 신라어 중간 정도 위치)... 학교문법에서는 이 견해를

소고기감자숙주양송이무른밥 닭고기고구마옥수수감자당근청경채양파찹쌀무른밥 대구살느타리근대양파흑미무른밥

갂다라는 16대 부족국가(Maha-Jana-pada) 시대에 아프가니스탄과 파키스탄 일대에 번성했던 국가로, B.C.6세기 다리우스 1세가 제국을 건설하면서 페르시아의 영향

모드 선택 표시 창에서 UNIT CONTROL 모드를 선택하고 SET 버튼을 눌렀을 경우 그림 5 와 같이 LCD 화면에 각 ICU 의 상태가

 break 문은 반복 루프를 빠져