투케이2K

4. (AndroidStudio/android/java) 인텐트(Intent) 화면 전환 시 액티비티 간 데이터 전송 실시 (Intent.putExtra) 본문

Android

4. (AndroidStudio/android/java) 인텐트(Intent) 화면 전환 시 액티비티 간 데이터 전송 실시 (Intent.putExtra)

투케이2K 2021. 1. 12. 08:10
반응형

/* =========================== */

[ 개발 환경 설정 ]

개발 툴 : AndroidStudio

개발 언어 : java

/* =========================== */

/* =========================== */

[소스 코드]

[AndroidManifest.xml]

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kr.co.test.twokproject">

    <!-- ==== 퍼미션 등록 ==== -->

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".A_IntentMain">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- ==== 추가 액티비티 등록 ==== -->
        <activity android:name=".A_IntentSub"/>

    </application>

</manifest>

[A_IntentMain]

package kr.co.test.twokproject;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class A_IntentMain extends AppCompatActivity {

	// ==== [전역 및 컴포넌트 선언] ====
	String data = "";

	TextView data_textview;
	Button ok_button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_a_intentmain);
		Log.d("---","---");
		Log.d("//===========//","================================================");
		Log.d("","\n"+"[A_IntentMain > onCreate() 메소드 : 액티비티 종료 실시]");
		Log.d("//===========//","================================================");
		Log.d("---","---");

		// ==== [컴포넌트 매칭] ====
		data_textview = (TextView) findViewById(R.id.data_textview);
		ok_button = (Button) findViewById(R.id.ok_button);

		// ==== [이벤트 정의] ====
		ok_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				/**[설 명]
				* 1. new Intent(현재 클래스, 이동할 클래스); 의미입니다
				* 2. Intent.putExtra(키값, 전송할 데이터); 의미입니다
				* 3. A_IntentMain 클래스에서 A_IntentSub 클래스로 인텐트 이동을 실시합니다 (화면 전환)
				* 4. startActivityForResult - 인텐트 이동 시작 및 데이터 전송 코드를 작성합니다
				* 5. finish - 인텐트 이동 종료를 의미합니다 (원래 화면으로 복귀)
				* 6. FLAG_ACTIVITY_NO_ANIMATION과 overridePendingTransition을 사용해서 애니메이션 효과를 제거합니다
				* 7. 참고 - 반드 시 인텐트 이동을 하기 위해서는 모든 클래스가 AndroidManifest.xml에 선언되어있어야합니다
				*/
				Intent intent = new Intent(A_IntentMain.this,A_IntentSub.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); //애니메이션 효과 없앤다
				intent.putExtra("name","투케이"); //이름은 String
				intent.putExtra("age",28); //나이는 int
				intent.putExtra("man",true); //성별 남자여부는 boolean
				startActivityForResult(intent,1);
				overridePendingTransition(0,0); //애니메이션 효과 없앤다
			}
		});

	}//메인 종료

	// ==== [A_IntentSub 인텐트 종료 시 넘어온 데이터를 받기 위한 메소드] ====
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		super.onActivityResult(requestCode,resultCode,data);
		try {
			if(requestCode == 1){ //A_IntentMain에서 인텐트 시작 시 작성한 requestCode 인 경우
				if(resultCode == 2){ //A_IntentSub에서 인텐트 종료 시 작성한 resultCode 인 경우
					String result = data.getStringExtra("confirm"); //키값 호출
					data_textview.append("\n");
					data_textview.append("응답값 : "+result+"\n");
				}
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
	}


	// ==== [액티비티 종료 메소드] ====
	@Override
	public void onDestroy(){
		super.onDestroy();
		Log.d("---","---");
		Log.d("//===========//","================================================");
		Log.d("","\n"+"[A_IntentMain > onDestroy() 메소드 : 액티비티 종료 실시]");
		Log.d("//===========//","================================================");
		Log.d("---","---");
	}

}//클래스 종료

[A_IntentSub]

package kr.co.test.twokproject;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class A_IntentSub extends AppCompatActivity {

	// ==== [전역 및 컴포넌트 선언] ====
	String data = "";

	TextView data_textview;
	Button ok_button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_a_intentsub);
		Log.d("---","---");
		Log.d("//===========//","================================================");
		Log.d("","\n"+"[A_IntentSub > onCreate() 메소드 : 액티비티 종료 실시]");
		Log.d("//===========//","================================================");
		Log.d("---","---");

		// ==== [컴포넌트 매칭] ====
		data_textview = (TextView) findViewById(R.id.data_textview);
		data_textview.append("\n");
		ok_button = (Button) findViewById(R.id.ok_button);

		// ==== 인텐트로 넘어온 데이터를 받기 위해 변수 선언 실시 ====
		String name = "";
		int age = 0;
		boolean sex = false;
		try {
			Intent intent = getIntent(); //getIntent() 를 사용해서 데이터를 받아온다
			name = intent.getStringExtra("name"); //키값 호출
			age = intent.getIntExtra("age",0); //키값 호출, 기본값
			sex = intent.getBooleanExtra("man",false); //키값 호출, 기본값
			if(name != null && name.length() > 0){ //비정상 데이터가 아닐 경우
				data_textview.append("이름 : "+name+"\n");
			}
			if(age != 0){
				data_textview.append("나이 : "+age+"\n");
			}
			if(sex != false){
				data_textview.append("남자여부 : "+sex+"\n");
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}

		// ==== [이벤트 정의] ====
		ok_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// ==== 인텐트 종료 및 데이터전송 실시 ====
				Intent intent = new Intent();
				intent.putExtra("confirm","정보확인");
				setResult(2, intent); //인텐트 종료 코드 지정
				finish();
				overridePendingTransition(0,0);
			}
		});

	}//메인 종료

	// ==== [액티비티 종료 메소드] ====
	@Override
	public void onDestroy(){
		super.onDestroy();
		Log.d("---","---");
		Log.d("//===========//","================================================");
		Log.d("","\n"+"[A_IntentSub > onDestroy() 메소드 : 액티비티 종료 실시]");
		Log.d("//===========//","================================================");
		Log.d("---","---");
	}

}//클래스 종료
​

[activity_a_intentmain.xml]

<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- ====== [타이틀 레이아웃] ====== -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:orientation="horizontal"
            android:background="#4d68a0"
            android:layout_marginBottom="5dp">
            <TextView
                android:id="@+id/title_text"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="[ A_IntentMain ]"
                android:textColor="#ffffff"
                android:textSize="23dp"
                android:textStyle="bold"
                android:gravity="center"/>
        </LinearLayout>

        <!-- ====== [몸체 레이아웃] ====== -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="#4d68a0"
            android:layout_marginTop="0dp"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="0dp"
            android:layout_marginBottom="0dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.3"
                android:orientation="horizontal" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1.7"
                android:orientation="horizontal"
                android:background="#ffffff"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginBottom="20dp">
                <TextView
                    android:id="@+id/data_textview"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:text="A_IntentMain 액티비티"
                    android:textColor="#000000"
                    android:textSize="20dp"
                    android:textStyle="bold"/>
            </LinearLayout>

            <Button
                android:id="@+id/ok_button"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.3"
                android:text="이 동"
                android:textStyle="bold"
                android:textSize="20dp"
                android:gravity="center"
                android:textColor="#000000"
                android:background="#ffffff"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginBottom="0dp"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.3"
                android:orientation="horizontal" />
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

[activity_a_intentsub.xml]

<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- ====== [타이틀 레이아웃] ====== -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:orientation="horizontal"
            android:background="#4d68a0"
            android:layout_marginBottom="5dp">
            <TextView
                android:id="@+id/title_text"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="[ A_IntentSub ]"
                android:textColor="#ffffff"
                android:textSize="23dp"
                android:textStyle="bold"
                android:gravity="center"/>
        </LinearLayout>

        <!-- ====== [몸체 레이아웃] ====== -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="#4d68a0"
            android:layout_marginTop="0dp"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="0dp"
            android:layout_marginBottom="0dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.3"
                android:orientation="horizontal" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1.7"
                android:orientation="horizontal"
                android:background="#ffffff"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginBottom="20dp">
                <TextView
                    android:id="@+id/data_textview"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:text="A_IntentSub 액티비티"
                    android:textColor="#000000"
                    android:textSize="20dp"
                    android:textStyle="bold"/>
            </LinearLayout>

            <Button
                android:id="@+id/ok_button"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.3"
                android:text="종 료"
                android:textStyle="bold"
                android:textSize="20dp"
                android:gravity="center"
                android:textColor="#000000"
                android:background="#ffffff"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginBottom="0dp"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.3"
                android:orientation="horizontal" />
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

/* =========================== */

[결과 출력]

[A_IntentMain에서 A_IntentSub로 인텐드 이동 및 데이터 전달 실시]

[A_IntentSub로에서 인텐트 종료 및 A_IntentMain로 데이터 전달 실시]

/* =========================== */

/* =========================== */

[요약 설명]

* 1. new Intent(현재 클래스, 이동할 클래스); 의미입니다

* 2. Intent.putExtra(키값, 전송할 데이터); 의미입니다

* 3. A_IntentMain 클래스에서 A_IntentSub 클래스로 인텐트 이동을 실시합니다 (화면 전환)

* 4. startActivityForResult - 인텐트 이동 시작 및 데이터 전송 코드를 작성합니다

* 5. finish - 인텐트 이동 종료를 의미합니다 (원래 화면으로 복귀)

* 6. FLAG_ACTIVITY_NO_ANIMATION과 overridePendingTransition을 사용해서 애니메이션 효과를 제거합니다

* 7. 참고 - 반드 시 인텐트 이동을 하기 위해서는 모든 클래스가 AndroidManifest.xml에 선언되어있어야합니다

/* =========================== */

반응형
Comments