Android
 Computer >> コンピューター >  >> プログラミング >> Android

Androidでアクティビティ間を画像を受け渡す方法をわかりやすく解説

はじめに

本記事では、Androidアプリであるアクティビティ(Activity)から別のアクティビティへ画像を受け渡す方法を解説します。ここでは、Intentに画像のリソースIDを格納して渡す、最もシンプルで確実な手法を紹介します。

手順1:新規プロジェクトの作成

Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要事項をすべて入力してプロジェクトを作成しましょう。

手順2:activity_main.xml の編集

res/layout/activity_main.xml に以下のコードを追加します。「Send Image」ボタンと、表示用の 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 に以下のコードを記述します。ボタンがタップされると、putExtra() で画像リソースのIDを Intent に格納し、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:SecondActivity の作成

空のアクティビティ(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

受信側では getIntent().getExtras() で Bundle を取得し、「resId」というキーで保存された画像リソースIDを取り出して ImageView にセットします。

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);
        }
    }
}

手順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スマートフォンをパソコンに接続済みであることを前提としています。Android Studioでプロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。モバイルデバイスを選択すると、端末に初期画面が表示されます。

Androidでアクティビティ間を画像を受け渡す方法をわかりやすく解説

仕組みのポイント

  • 送信側: intent.putExtra("resId", R.drawable.image) で画像のリソースIDをIntentに格納します。
  • 受信側: getIntent().getExtras() でBundleを取得し、bundle.getInt("resId") でIDを取り出します。
  • 表示: 取得したIDを imageView.setImageResource(resId) に渡すだけで画像が表示されます。

Bitmapオブジェクトをそのまま受け渡すと、Binderトランザクションのデータサイズ上限を超えて TransactionTooLargeException が発生する恐れがあります。リソースIDだけを渡すこの方法であれば、軽量かつ安全にアクティビティ間で画像を共有できます。

  1. Androidでアクティビティからフラグメントへ変数を渡す方法を徹底解説

    はじめに この記事では、Androidアプリ開発においてアクティビティ(Activity)からフラグメント(Fragment)へ変数を渡す方法を、実際のコード例とともに段階的に解説します。 アクティビティからフラグメントへのデータ受け渡しには、Bundleを使うのが基本です。アクティビティ側でsetArguments()メソッドによりBundleをフラグメントにセットし、フラグメント側でgetArguments()メソッドを使って値を取り出します。 手順1:新規プロジェクトを作成する Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Projec

  2. 【Android】1つのフラグメントから別のフラグメントへデータを送信する方法(インターフェース活用の実装例)

    はじめに このチュートリアルでは、Androidアプリで1つのフラグメント(Fragment)から別のフラグメントへデータを送信する方法を解説します。フラグメント同士は直接通信することができません。そこで本記事では、カスタムインターフェース「SendMessage」を定義し、ホストとなるMainActivityを仲介してデータを受け渡す、定番かつ推奨されるパターンを紹介します。 具体的には、タブで切り替えられる2つのフラグメントを用意し、1つ目のフラグメントで入力したテキストをボタン操作で2つ目のフラグメントに表示させるサンプルアプリを作成します。 ステップ1:新しいプロジェクトを作成する