Androidでアクティビティからフラグメントへ変数を渡す方法を徹底解説
はじめに
この記事では、Androidアプリ開発においてアクティビティ(Activity)からフラグメント(Fragment)へ変数を渡す方法を、実際のコード例とともに段階的に解説します。
アクティビティからフラグメントへのデータ受け渡しには、Bundleを使うのが基本です。アクティビティ側でsetArguments()メソッドによりBundleをフラグメントにセットし、フラグメント側でgetArguments()メソッドを使って値を取り出します。
手順1:新規プロジェクトを作成する
Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。
手順2:activity_main.xml にコードを追加する
res/layout/activity_main.xml に以下のコードを記述します。メッセージ入力用のEditText、送信用のButton、そしてフラグメントを表示するためのFrameLayoutを配置しています。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" android:gravity="center" android:padding="2dp" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_marginTop="20sp" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="ENTER YOUR MESSAGE" /> <Button android:id="@+id/btnSendData" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send data" /> <FrameLayout android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="match_parent"> </FrameLayout> </LinearLayout>
手順3:MainActivity.java を実装する
src/MainActivity.java に以下のコードを追加します。ボタンがクリックされると、EditTextに入力された文字列をBundleに格納し、setArguments()でフラグメントに渡したうえで、FrameLayoutにフラグメントを追加しています。
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
final MyFragment myFragment = new MyFragment();
button = findViewById(R.id.btnSendData);
editText = findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putString("message", editText.getText().toString());
myFragment.setArguments(b);
fragmentTransaction.add(R.id.frameLayout, myFragment).commit();
}
});
}
}
手順4:フラグメントを作成する
新しいフラグメントクラスを作成し、以下のコードを追加します。
MyFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MyFragment extends Fragment {
TextView textView;
public MyFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_my, container, false);
textView = view.findViewById(R.id.textView);
Bundle bundle = getArguments();
String message = bundle.getString("message");
textView.setText(message);
return view;
}
}
fragment_my.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <TextView android:id="@+id/textView" android:textSize="30dp" android:textStyle="bold" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
フラグメント側ではgetArguments()でBundleを取得し、キー「message」に対応する文字列を取り出してTextViewに表示しています。
手順5:AndroidManifest.xml を確認する
androidManifest.xml に以下のコードを追加します。
<?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=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
補足:AndroidX環境で動かす場合の注意点
上記のサンプルコードは旧サポートライブラリ(android.support)を使用しています。現在のAndroid Studioで新規プロジェクトを作成した場合はAndroidXが標準となるため、import文を以下のように読み替えてください。
- android.support.v4.app.FragmentManager → androidx.fragment.app.FragmentManager
- android.support.v4.app.FragmentTransaction → androidx.fragment.app.FragmentTransaction
- android.support.v7.app.AppCompatActivity → androidx.appcompat.app.AppCompatActivity
- android.support.v4.app.Fragment → androidx.fragment.app.Fragment
アプリを実行してみよう
それでは、アプリを実行してみましょう。ここでは、実機のAndroidスマートフォンをPCに接続しているものとして説明を進めます。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。実行デバイスとして自分のモバイル端末を選択すると、端末に以下のような初期画面が表示されます。

-
Androidアプリでフラグメントからアクティビティのメソッドを呼び出す方法【サンプルコード付き】
このチュートリアルでは、Androidアプリにおいてフラグメントからアクティビティのメソッドを呼び出す実装方法を解説します。フラグメントは単体では動作せず、必ずアクティビティ上に存在するため、getActivity()で親アクティビティの参照を取得し、適切な型にキャストすることで、アクティビティのpublicメソッドを直接呼び出すことができます。 実装手順 ステップ1:新規プロジェクトの作成 Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。 ステップ2:activ
-
Androidでアクティビティ間を画像を受け渡す方法をわかりやすく解説
はじめに 本記事では、Androidアプリであるアクティビティ(Activity)から別のアクティビティへ画像を受け渡す方法を解説します。ここでは、Intentに画像のリソースIDを格納して渡す、最もシンプルで確実な手法を紹介します。 手順1:新規プロジェクトの作成 Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要事項をすべて入力してプロジェクトを作成しましょう。 手順2:activity_main.xml の編集 res/layout/activity_main.xml に以下のコードを追加します。「Send