[Android] 프로젝트 생성 및 Activity를 추가해 버튼 클릭시 넘어가기/응용
1. Android Studio 를 이용해 프로젝트 생성하기
안드로이드 스튜디오에서 New Project를 눌러 프로젝트 마법사를 띄웁니다.
Application name : 만들고자 하는 앱의 이름을 입력합니다.
Company domain : 제작사 도메인 (팀 또는 회사에 소속되어있다면 적어줍니다.)
Project location : 프로젝트 파일들이 저장될 경로입니다.
Next를 눌러 다음 단계로 갑니다.
개발킷 (SDK) 를 선택합니다.
휴대폰 앱을 만들어야 하기 때문에 Phone and Tablet을 선택했습니다.
API를 고를 수 있는데, 선택창 바로 밑에 영어로 해당 API버전을 타겟으로 제작할 경우 약 몇%의 기기들에서 실행 가능한 지 알려주고 있습니다.
Next를 눌러 다음 단계로 갑니다.
MainActivity의 템플릿(?)을 고를 수 있는 창입니다. 비어있는 액티비티 (Empty Activity)를 선택했습니다.
Next를 눌러 마지막 단계로 갑니다.
MainActivity로 사용할 Activity의 이름을 입력합니다. Layout으로 설정할 리소스 파일 이름도 입력할 수 있습니다. 다른 Activity들과 섞였을 때에도 알아볼 수 있도록 Activity의 이름과 Layout의 이름을 같거나 비슷하게 하여 연관있어 보이게 하는것이 좋습니다.
2. Activity 추가하기
좌측의 Project 탐색창에서 app > java > 프로젝트명 디렉토리에 마우스 오른쪽 버튼을 누르고 New > Activity > Empty Activity 를 눌러 추가합니다.
Activity 추가 창이 뜨면, 아까전과 같이 새로운 Activity Name과 Layout Name을 설정합니다. (Activity Name만 바꿔도 Layout Name이 자동으로 변화합니다)
(Launcher Activity 체크는 처음으로 실행되는 Activity로 지정할 것인지 여부입니다.)
Finish를 눌러 두번째 Activity를 추가합니다.
3. 버튼 및 레이아웃 배치하기
좌측의 Project 탐색기에서 res > layout > 첫번째 Activity의 레이아웃.xml 을 더블클릭하여 엽니다.
xml 파일의 text를 보면, Default로 레이아웃이 android.support.constraint.ConstraintLayout으로 설정되어 있음을 볼 수 있습니다. 이를 RelativeLayout으로 바꿔봅니다.
(RelativeLayout은 레이아웃 안의 위젯들을 상대적 위치로 배치해 주는 레이아웃 입니다. ex : A를 B의 왼쪽/오른쪽에 배치한다.)
버튼을 추가해 봅니다. 하단의 소스코드를 RelativeLayout의 괄호가 끝나기 전에 ( "</RelativeLayout>" 전에) 삽입합니다.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:id="@+id/btn_sample"
android:text="버튼내용"/>
android:layout_width 버튼의 너비 길이 입니다. wrap_content는 내용에 맞게 크기를 맞추고, match_parent는 부모의 너비를 사용합니다.
android:layout_height 버튼의 높이 길이 입니다. wrap_content는 내용에 맞게 크기를 맞추고, match_parent는 부모의 높이를 사용합니다.
android:gravity="center" 버튼의 글씨를 가운데로 정렬합니다.
android:id="@+id/아이디" 버튼의 id값을 지정합니다.
android:text="버튼내용" 버튼위에 표시되는 글씨를 지정합니다.
버튼을 화면의 가운데 배치하고 싶다면, <RelativeLayout의 시작괄호가 닫히기 전에 하단의 소스코드를 추가합니다.
android:gravity="center"
버튼이 가운데로 갔음을 확인합니다.
4. 버튼에 onClickListener 연결하여 Click이벤트 설정하기
프로젝트 탐색창에서 app > java > 프로젝트명 디렉토리 > 메인 엑티비티.java 파일을 엽니다.
button변수를 private Button 자료형으로 선언하고, onCreate 함수 안에서 button을 아까 layout에서 만들었던 버튼을 가리키도록 지정 합니다.
onStart 함수 안에서 버튼 클릭시 이벤트를 setOnClickListener함수를 사용해 연결합니다.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
Intent를 생성할 때에는 첫번째 인수로 Intent가 실행될 자신의 context, 두번째 인수로 실행시킬 Activity의 클래스를 집어넣습니다.
startActivity 함수를 이용해 Main2Activity로 설정해놓은 Intent를 실행시킵니다.
이후 디버깅이나 컴파일을 하고 버튼을 누르면 다음창으로 넘어가 짐을 볼 수 있습니다.
두번째 창으로 올바르게 넘어갔는지 확인하기 위해, Toast 메시지를 띄워보겠습니다.
두번째 Activity의 java파일을 열고, onCreate함수의 맨 밑에 밑의 소스코드를 추가합니다.
Toast.makeText(Main2Activity.this,"두번째 Activity 입니다.",Toast.LENGTH_SHORT).show();
이후 다시 디버깅 또는 컴파일을 하고 버튼을 누르면, 두번째 창으로 넘어가면서 메시지가 뜨는것을 볼 수 있습니다.
다음으로, 위 내용들을 조금 응용해 간단한 자기소개 App을 만들어 보았습니다.
activity_main.xml
<?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="com.yunjun.cadi_0512.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:foregroundGravity="center" android:orientation="vertical"> <ImageView android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/me" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginVertical="10dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:gravity="center" android:layout_height="wrap_content" android:text="이 름" android:layout_marginHorizontal="15dp"/> <TextView android:layout_width="match_parent" android:gravity="center" android:layout_height="wrap_content" android:text="나 이" android:layout_marginHorizontal="15dp"/> <TextView android:layout_width="match_parent" android:gravity="center" android:layout_height="wrap_content" android:text="파 트" android:layout_marginHorizontal="15dp"/> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="최 윤 준"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingHorizontal="15dp" android:gravity="center" android:text="2 5"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingHorizontal="15dp" android:gravity="center" android:text="개발A"/> </LinearLayout> </LinearLayout> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/btn_next_page" android:text="학교"/> </LinearLayout> </RelativeLayout>
activity_second.xml
<?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="com.yunjun.cadi_0512.SecondActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <ImageView android:id="@+id/img_school" android:layout_width="150dp" android:layout_height="150dp" android:layout_gravity="center" android:layout_marginVertical="15dp" android:src="@drawable/suwon" /> <Button android:id="@+id/btn_school" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="웹페이지" /> </LinearLayout> </RelativeLayout>
MainActivity.java
package com.yunjun.cadi_0512; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.btn_next_page); } @Override protected void onStart() { super.onStart(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this,SecondActivity.class); startActivity(intent); finish(); } }); } }
SecondActivity.java
package com.yunjun.cadi_0512; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class SecondActivity extends AppCompatActivity { Button btn_school; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); btn_school = (Button) findViewById(R.id.btn_school); } @Override protected void onStart() { super.onStart(); btn_school.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suwon.ac.kr/"))); } }); } }