Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 한 액티비티의 이미지를 다른 액티비티로 전달하는 방법

개요

이 튜토리얼에서는 안드로이드에서 한 액티비티(Activity)에 있는 이미지를 인텐트(Intent)를 활용해 다른 액티비티로 전달하는 방법을 단계별로 알아봅니다. 핵심은 Intent의 putExtra() 메서드로 이미지 리소스 ID를 담아 전달하고, 받는 쪽 액티비티에서 getExtras()로 꺼내 화면에 표시하는 것입니다.


구현 단계

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project로 이동한 뒤, 새 프로젝트 생성에 필요한 세부 정보를 모두 입력하여 프로젝트를 만듭니다.

2단계 — activity_main.xml 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 이미지 전송용 버튼과 이미지를 표시할 ImageView가 포함되어 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="16dp"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/btnSend"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="40dp"
      android:onClick="SendImage"
      android:text="Send Image" />
   <ImageView
      android:id="@+id/imageView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_below="@id/btnSend"
      android:layout_marginTop="10dp"
      android:src="@drawable/image" />
</RelativeLayout>

3단계 — MainActivity.java 작성

src/MainActivity.java에 다음 코드를 추가합니다. 버튼을 클릭하면 Intent 객체에 putExtra()로 이미지 리소스 ID(resId)를 담아 SecondActivity를 시작합니다.

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   public void SendImage(View view) {
      Intent intent = new Intent(MainActivity.this, SecondActivity.class);
      intent.putExtra("resId", R.drawable.image);
      startActivity(intent);
   }
}

4단계 — 두 번째 액티비티 생성

빈 액티비티(Empty Activity)를 하나 생성한 후 아래와 같이 코드를 작성합니다.

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="8dp"
   tools:context=".SecondActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="40dp"
      android:text="Second Activity"
      android:textSize="24sp"
      android:textStyle="bold"/>
   <ImageView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_below="@id/textView"
      android:layout_marginTop="5dp"
      android:id="@+id/imageView2"/>
</RelativeLayout>

SecondActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class SecondActivity extends AppCompatActivity {
   ImageView imageView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_second);
      imageView = findViewById(R.id.imageView2);
      Bundle bundle = getIntent().getExtras();
      if (bundle != null) {
         int resId = bundle.getInt("resId");
         imageView.setImageResource(resId);
      }
   }
}

SecondActivity에서는 getIntent().getExtras()로 전달된 데이터 번들을 받고, getInt("resId")로 이미지 리소스 ID를 꺼낸 뒤 setImageResource()를 호출해 ImageView에 해당 이미지를 표시합니다.

5단계 — AndroidManifest.xml 설정

androidManifest.xml에 다음 코드를 추가하여 SecondActivity를 등록합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
   <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=".SecondActivity"></activity>
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 실행 기기 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 한 액티비티의 이미지를 다른 액티비티로 전달하는 방법

참고 사항

이 예제는 이미지 리소스 ID(int 값)를 전달하는 방식으로, 직렬화 없이 가볍게 데이터를 넘길 수 있는 가장 간단한 방법입니다. 반면 카메라로 촬영한 사진이나 갤러리에서 선택한 이미지처럼 실제 비트맵(Bitmap) 객체를 전달해야 하는 경우에는 주의가 필요합니다. 비트맵을 Intent에 그대로 담으면 용량 제한 초과로 TransactionTooLargeException이 발생할 수 있으므로, 큰 이미지는 임시 파일로 저장한 뒤 파일 경로나 URI를 전달하는 방식을 사용하는 것이 좋습니다.