Starting Another Activity 다른 액티비티 시작하기
This lesson teaches you to 이 단원에서는 다음을 가르칩니다
1. Respond to the Send Button Send 버튼에 응답하기
2. Build an Intent Intent 빌드 하기
3. Create the Second Activity 두 번째 액티비티 만들기
4. Receive the Intent Intent 수신하기
5. Display the Message 메시지 표시하기
You should also read
After completing the previous lesson, you have an app that shows an activity (a single screen) with a text
field and a button. In this lesson, you’ll add some code to MainActivity that starts a new activity when
the user clicks the Send button.
앞선 단원(previous lesson)을 완료하면, 텍스트 필드(text field)와 단추(button)를 가진 한 activity(단일 화면)를 표시하는 app을 갖게 됩니다. 이 단원에서는 사용자가 Send(전송) 버튼을 클릭하면 새로운 activity를 시작하는 MainActivity.java
파일에 약간의 코드를 추가합니다.
Respond to the Send Button Send 버튼에 응답하기
1.
In Android Studio,
from the res/layout directory,
edit the content_main.xml file.
안드로이드 스튜디오의 res/layout 디렉토리에 있는 content_main.xml 파일을 편집하십시오.
2.
To the <Button> element, add the android:onClick attribute.
<Button>엘리먼트에 android:onClick속성을 추가하십시오.
res/layout/content_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
The android:onClick attribute’s value, "sendMessage",
is the name of a method in your activity that the system calls when the user
clicks the button.
android:onClick 속성 값인 "sendMessage"는 사용자가 버튼을 클릭하면 시스템이 호출하는 activity안의 메소드 이름 입니다.
3.
In the java/com.example.hans.myapplication directory,
open the MainActivity.java file.
java/com.example.hans.myapplication 디렉토리에서, MainActivity.java 파일을 여십시오.
4.
Within the MainActivity class, add the sendMessage() method stub shown below.
MainActivity 클래스 안에, 아래의 sendMessage() 메소드 stub를 추가하십시오.
java/com.example.hans.myapplication/MainActivity.java
/** Called when the
user clicks the Send button 사용자가 Send 버튼을 클릭하면 호출됨 */
public void sendMessage(View view) {
// Do something in response to button 버튼에 대한 응답으로 무엇인가를 함
}
In order for the system to match this method to the
method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:
시스템이 이 메소드를 android:onClick에 부여된 메소드 이름과 매칭시켜야 하기 때문에, 아래처럼 signature가 정확 해야 합니다. 특히 메소드는 다음과 같아야 합니다:
o Be public public 이어야 함
o Have a void return value 리턴값이 void 이어야 함
o Have a View as the only parameter (this will be the View that was clicked) 유일한 패러미터로 View를 가져야 함(this는 클릭되었던 View가 될 것임)
Next, you’ll fill in this method to read the contents of the text field
and deliver that text to another activity.
다음에, text field의 컨텐츠를 읽도록 하기 위하여 이 메소드 안을 채우면, 해당 text를 다른 activity로 배달할 것입니다.
Build an Intent Intent 빌드 하기
1.
In MainActivity.java, inside the sendMessage() method, create an Intent to start an activity called DisplayMessageActivity with
the following code:
MainActivity.java의 sendMessage() 메소드 안에, 다음 코드를 가진 DisplayMessageActivity란 이름의 액티비티를 시작시키기 위한 Intent를 만드십시오:
java/com.example.hans.myapplication/MainActivity.java
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
}
Intents
An Intent is an object that provides runtime binding between separate
components (such as two activities). The Intent represents an app’s "intent to do something." You can use
intents for a wide variety of tasks, but most often they’re used to start
another activity. For more information, see Intents and Intent Filters.
Intent는 별개 구성요소(예, 2개의 activity) 간 런타임 바인딩을 제공하는 객체입니다. Intent는 "뭔가를 수행하고자 하는 app의 의도" 입니다. 다양한 작업 용도로 사용할 수 있지만, 다른 activity를 시작하는 용도로 가장 많이 사용됩니다. 자세한 내용은 Intents와 Intent Filters를 참조하십시오.
Note: The reference to DisplayMessageActivity will
raise an error if you’re using an IDE such as Android Studio because the class
doesn’t exist yet. Ignore the error for now; you’ll create the class soon.
주: 안드로이드 스튜디오와 같은 IDE를 사용할 때 DisplayMessageActivity에 대한 참조는 오류를 발생시키는데, 그 이유는 아직 클래스가 존재하지 않기 때문입니다. 이제 오류를 무시하고; 클래스를 만드십시오.
The constructor used here takes two parameters: 여기 사용된 생성자는 2개의 패러미터를 갖고 있습니다:
o
A Context as its first parameter (this is
used because the Activity class is a subclass of Context)
그 첫 패러미터인 Context(Activity 클래스가 Context의 하위클래스 이기 때문에 this가 사용됨)
o
The Class of the
app component to which the system should deliver the Intent (in this case, the activity that should be started)
시스템이 Intent (이 경우, 시작되어야 할 activity)를 배달해야 하는 app
구성요소의 Class
Android Studio indicates that you must import the Intent class. 안드로이드 스튜디오는 Intent 클래스를 import 해야 함을 가리킵니다.
2. At the top of the file, import the Intent class: 파일의 맨 위에, Intent 클래스가 자동으로 import 되어 있습니다:
java/com.example.hans.myapplication/MainActivity.java
import android.content.Intent;
Tip: In Android Studio, press Alt + Enter (option +
return on Mac) to import missing classes.
팁: 안드로이드 스튜디어에서, 빠진 클래스들을 import 하려면 Alt + Enter를 누르십시오 (option + return on Mac)
3.
Inside the sendMessage() method, use findViewById() to get the EditText element.
sendMessage() 메소드 안에서, EditText 엘리먼트를 얻기 위하여 findViewById()를 사용하십시오.
java/com.example.hans.myapplication/MainActivity.java
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
}
4.
At the top of the
file, import the EditText class. 파일 꼭대기에, EditText class가 자동으로 import 되어 있습니다.
import android.widget.EditText;
In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
Android Studio에서, 빠진 클래스들을 import 하려면 Alt + Enter를 누르십시오 (option + return on Mac)
5.
Assign the text to a
local message variable, and use
the putExtra() method to add its text value to the intent.
local message 변수에 텍스트를 할당하고, intent에 텍스트 값을 추가하기 위하여 putExtra() 메소드를 사용하십시오.
java/com.example.hans.myapplication/MainActivity.java
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);
}
An Intent can carry data types as key-value pairs called extras.
The putExtra() method takes the key name in the first parameter
and the value in the second parameter.
Intent는 extras로 불리는 키-값 쌍으로 데이터 타입을 운반할 수 있습니다. putExtra() method는 첫째 패러미터 안에 키 이름을 취하고, 두 번째 패러미터 안에 값을 취합니다.
6.
At the top of
the MainActivity class, add
the EXTRA_MESSAGE definition as
follows:
MainActivity 클래스의 꼭대기에, 다음과 같이 EXTRA_MESSAGE 정의(definition)를 추가하십시오:
java/com.example.hans.myapplication/MainActivity.java
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.hans.myapplication.MESSAGE";
...
}
For the next activity to query the extra data, you should
define the key for your intent's extra using a public constant. It's generally
a good practice to define keys for intent extras using your app's package name
as a prefix. This ensures the keys are unique, in case your app interacts with
other apps.
엑스트라 데이터를 조회하기 위한 다음 액티비티와 관련하여, public 상수를 사용하여 intent의 엑스트라에 대한 키를 정의해야 합니다. 접두사로 앱의 패키지 이름을 사용하여, intent 엑스트라에 대한 키를 정의하는 것은 일반적으로 좋은 습관입니다. 이렇게 하면 앱이 다른 앱과 상호 작용하는 경우, 키의 유일성을 보장합니다.
7.
In the sendMessage() method, to finish the intent,
call the startActivity() method, passing it the Intent object created in step 1.
sendMessage() 메소드에서, intent를 종료하려면, startActivity() 메소드를 호출해서, 그것을 스텝1에서 생성된 Intent 객체로 보내십시오.
With this new code, the complete sendMessage() method
that's invoked by the Send button now looks like this:
이 새 코드를 가진, Send 버튼이 인보크한 완전한 sendMessage() method는 아래와 같습니다:
java/com.example.hans.myapplication/MainActivity.java
/**
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);
}
The system receives this call and starts an instance of the Activity specified by the Intent. Now you need to create the DisplayMessageActivity class
in order for this to work.
시스템이 this
call을 수신하면 Intent가 규정한 Activity의 인스턴스가 시작됩니다. 이제 this가 작동하도록 하기 위하여 DisplayMessageActivity 클래스를 만들어야 합니다.
Create the Second Activity 두 번째 액티비티 만들기
All subclasses of Activity must implement the onCreate() method. This method is where the activity receives
the intent with the message, then renders the message. Also, the onCreate() method must define the activity layout with the setContentView() method. This is where the activity performs the
initial setup of the activity components.
Activity의 모든 하위클래스는 onCreate() 메소드를 구현해야 합니다. 이 메소드는, 액티비티가 메시지를 가진 intent를 수신하고, 그런 다음 메시지를 렌더링 하는 곳입니다. 또한, onCreate() method는 setContentView () 메소드를 가진 액티비티 레이아웃을 정의해야 합니다. 이것은 액티비티가 액티비티 구성요소의 초기 설정을 수행하는 곳입니다.
Create a new activity using Android Studio
Figure 1. The new activity wizard in Android Studio. 안드로이드 스튜디오 내의 신규 액티비티 마법사
Android Studio includes a stub for the onCreate() method when you create a new activity.
Android Studio에는 신규 액티비티를 만들 때 onCreate() method에 대한 stub가 포함됩니다.
1.
In Android Studio, in
the java directory, select the
package, com.mycompany.myfirstapp, right-click, and select New
> Activity > Blank Activity.
Android Studio의, java directory에서, 패키지 com.example.hans.myapplication을 선택한 다음, right-click하고, New >
Activity > Blank Activity를 선택하십시오.
2. In the Choose options window, fill in the activity details:
o Activity Name: DisplayMessageActivity
o Layout Name: activity_display_message
o Title: DisplayMessageActivity
o Hierarchical Parent: com.mycompany.myfirstapp.MainActivity
o Package name: com.example.hans.myapplication
Click Finish.
3. Open the DisplayMessageActivity.java file. DisplayMessageActivity.java file을 여십시오.
The class already includes an implementation of the
required onCreate() method. You will update the implementation of this
method later. It also includes an implementation of onOptionsItemSelected(), which handles the app bar's Up behavior.
Keep these two methods as they are for now.
요구되는 onCreate() method 구현이 이미 클래스에 포함되어 있습니다. 후에 이 메소드 구현을 업데이트될 것입니다. 이것에는 onOptionsItemSelected()의 구현도 포함되어 있는데, 이것은 app bar의 Up behavior를 처리합니다. Keep these two methods as they are for now.
4. Remove the onCreateOptionsMenu() method. onCreateOptionsMenu() method를 제거하십시오.
You won't need it for this app. 이 앱에는 이것이 필요없습니다.
If you're developing with Android Studio, you can run the app now, but not
much happens. Clicking the Send button starts the second activity, but it uses
a default "Hello world" layout provided by the template. You'll soon
update the activity to instead display a custom text view.
안드로이드 스튜디오로 개발하는 경우, 이제 앱을 실행할 수 있지만, 많이는 실행하지 않습니다. 보내기 버튼을 클릭하면 두 번째 액티비티가 시작되지만, 템플릿이 제공하는 기본 "Hello
World" 레이아웃을 사용합니다. 곧 대신 사용자 정의 텍스트보기를 표시 할 수 있는 Activity을 업데이트합니다.
Create the activity without Android Studio 안드로이드 스튜디오 없이 액티비티 만들기
If you're using a different IDE or the command line tools, do the following:
1.
Create a new file
named DisplayMessageActivity.java in
the project's src/ directory, next
to the originalMainActivity.java file.
Create a new file named DisplayMessageActivity.java in
the project's src/ directory, next
to the originalMainActivity.java file.
2. Add the following code to the file:
public class DisplayMessageActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//
Handle app bar item clicks here. The app bar
//
automatically handles clicks on the Hans/Up button, so long
// as
you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() { }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView
= inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
Note: If you are using an IDE other than Android Studio, your project does not contain theactivity_display_message layout that's requested by setContentView(). That's OK because you will update this method later and won't be using that layout.
3. To your strings.xml file, add the new activity's title as follows:
<resources>
...
<string name="title_activity_display_message">My Message</string>
</resources>
4. In your manifest file, AndroidManifest.xml, within the Application element, add the <activity> element for your DisplayMessageActivity class, as follows:
<application ... >
...
<activity
android:name="com.mycompany.myfirstapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.mycompany.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.mycompany.myfirstapp.MainActivity" />
</activity>
</application>
The android:parentActivityName attribute declares the name of this activity's
parent activity within the app's logical hierarchy. The system uses this value
to implement default navigation behaviors, such as Up navigation on Android 4.1 (API level 16) and higher. You can provide the same
navigation behaviors for older versions of Android by using the Support Library and adding the <meta-data> element as shown here.
android:parentActivityName 속성은 앱의 논리적 계층 내부에서의 이 Activity의 부모 Activity의 이름을 선언합니다. 이 시스템은 안드로이드 4.1 (API 레벨 16) 이상 최대 탐색과 같은 기본 탐색 동작을 구현하기 위해이 값을 사용합니다. Support Library를 사용하여 다음과 같이 <meta-data> 요소를 추가하여 안드로이드의 이전 버전에 대해 동일한 탐색 동작을 제공 할 수 있습니다.
Note: Your Android SDK should already include the latest
Android Support Library, which you installed during the Adding SDK Packages step. When using the templates in Android Studio, the Support
Library is automatically added to your app project (you can see the library's
JAR file listed under Android Dependencies). If you're not using
Android Studio, you need to manually add the library to your project—follow the
guide for setting up the Support Library then return here.
참고: 안드로이드 SDK는 이미 추가 SDK 패키지 단계에서 설치한 최신 안드로이드 지원 라이브러리를 포함해야 합니다. 안드로이드 스튜디오에서 템플릿을 사용하는 경우, 지원 라이브러리가 자동으로 앱 프로젝트에 추가됩니다(라이브러리의 JAR 파일은 안드로이드 종속성 아래에 나열 볼 수 있습니다). 안드로이드 스튜디오를 사용하지 않는 경우, 수동으로에 라이브러리를 추가할 필요가 여기에 반환 지원 라이브러리를 forsetting 가이드를 프로젝트 수행합니다.
If you're using a different IDE than Android Studio, don't worry that the
app won't yet compile. You'll soon update the activity to display a custom text
view.
If you're using a different IDE than Android Studio, don't worry that the app won't
yet compile. You'll soon update the activity to display a custom text view
Receive the Intent Intent
수신하기
Every Activity is invoked by an Intent, regardless of how the user navigated there. You can get the Intent that started your activity by calling getIntent() and retrieve the data contained within the intent.
모든 Activity는 사용자가 거기를 네비게이트하는 방법과 관련없이, Intent에 의하여 인보크됩니다. You can get
the Intent that started your activity by calling getIntent() and retrieve the data contained within the intent.
1.
In the java/com.mycompany.myfirstapp directory, edit
the DisplayMessageActivity.java file.
In the java/com.mycompany.myfirstapp directory,
edit the DisplayMessageActivity.java file
2. In the onCreate() method, remove the following line: onCreate() method 안에서 다음 라인을 제거하십시오.
setContentView(R.layout.activity_display_message);
3. Get the intent and assign it to a local variable. Intent를 얻은 다음 그것을 로컬 변수에 할당하십시오.
Intent intent = getIntent();
4. At the top of the file, import the Intent class. 파일 꼭대기에 Intent 클래스가 자동으로 import 되어 있습니다.
In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
5.
Extract the message
delivered by MainActivity with
the getStringExtra() method.
getStringExtra() method로 MainActivity가 배달한 메시지를 추출하십시오.
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
Display the Message 메시지 표시하기
1. In the onCreate() method, create a TextView object.
TextView textView = new TextView(this);
2. Set the text size and message with setText().
textView.setTextSize(40);
textView.setText(message);
3. Then add the TextView as the root view of the activity’s layout by passing it to setContentView().
setContentView(textView);
4. At the top of the file, import the TextView class.
In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
The complete onCreate() method for DisplayMessageActivity now looks like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent intent로부터 메시지를 가져옵니다
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view text view를 만듭니다
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout 액티비티 레이아웃으로 text view를 설정합니다
setContentView(textView);
}
You can now run the app. When it opens, type a message in the text field,
click Send, and the message appears on the second activity.
이제 앱을 가동할 수 있습니다. 이것이 열리면 텍스트 필드에 메시지를 타입하고, Send를 클릭하면, 두 번째 activity에 메시지가 나타납니다.
Figure 2. Both activities in the final app, running on Android 4.4.
That's it, you've built your first Android app!
To learn more, follow the link below to the next class.
Next class: Supporting Different Devices
public abstract class
Context
extends Object
↳ |
android.content.Context |
|
AbstractInputMethodService, AccessibilityService, AccountAuthenticatorActivity, ActionBarActivity, Activity, ActivityGroup, AliasActivity, AppCompatActivity, Application, BackupAgent, BackupAgentHelper, CameraPrewarmService, CarrierMessagingService, and 38 others.
|
Class Overview
Interface to global
information about an application environment. This is an abstract class whose
implementation is provided by the Android system. It allows access to
application-specific resources and classes, as well as up-calls for
application-level operations such as launching activities, broadcasting and
receiving intents, etc.
애플리케이션
환경에
대한
글로벌
정보에
대한
Interface. Context는 안드로이드
시스템이
제공하는
구현인
추상
클래스
입니다. Context를 이용하면, activity시작, intent
방송
및
수신
등과
같은
애플리케이션-레벨 운영에
대한 up-call은 물론, 애플리케이션-특정
리소스
및
클래스에
대한
접근이
가능하게
됩니다.
Summary
Constants |
|||||||||||
Use
with |
|||||||||||
Use
with |
|||||||||||
Use
with |
|||||||||||
Use
with |
'앱 개발하기' 카테고리의 다른 글
간단한 사용자 인터페이스 구축하기 (0) | 2015.12.14 |
---|---|
앱(app) 가동하기 (0) | 2015.12.14 |
안드로이드 프로젝트 만들기 (0) | 2015.12.14 |
안드로이드 스튜디오는 안드로이드 앱을 개발하는 공식 IDE 입니다 (0) | 2015.12.14 |
안드로이드 스튜디오 설치하기 (0) | 2015.12.14 |
댓글