Androidアプリでフラグメントからアクティビティのメソッドを呼び出す方法【サンプルコード付き】
このチュートリアルでは、Androidアプリにおいてフラグメントからアクティビティのメソッドを呼び出す実装方法を解説します。フラグメントは単体では動作せず、必ずアクティビティ上に存在するため、getActivity()で親アクティビティの参照を取得し、適切な型にキャストすることで、アクティビティのpublicメソッドを直接呼び出すことができます。
実装手順
ステップ1:新規プロジェクトの作成
Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。
ステップ2:activity_main.xmlにコードを追加
res/layout/activity_main.xmlに以下のコードを記述します。フラグメントを配置するためのFrameLayoutを用意しています。
<?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=".MainActivity"> <FrameLayout android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
ステップ3:MainActivity.javaにコードを追加
src/MainActivity.javaに以下のコードを記述します。ここでは、フラグメントから呼び出されるpublicメソッド「FragmentMethod()」を定義し、トーストを表示するだけのシンプルな処理を行っています。
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, new SampleFragment()).commit();
}
public void FragmentMethod() {
Toast.makeText(MainActivity.this, "Method called From Fragment", Toast.LENGTH_LONG).show();
}
}
ステップ4:フラグメントクラスの作成
新しいフラグメントクラスを作成し、以下のコードを追加します。
SampleFragment.java
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sample, container, false);
((MainActivity) getActivity()).FragmentMethod();
return view;
}
}
ここでのポイントは「((MainActivity) getActivity()).FragmentMethod();」の行です。getActivity()によってフラグメントが紐づいているアクティビティを取得し、MainActivity型へキャストすることで、アクティビティ側のメソッドを呼び出しています。
fragment_sample.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" tools:context=".SampleFragment"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Calling a simple method from Fragment" android:textAlignment="center" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout>
ステップ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>
アプリを実行して動作を確認する
それでは、アプリを実行してみましょう。実際のAndroid端末をパソコンに接続していることを前提とします。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。実行デバイスとして自分のモバイル端末を選択すると、端末に以下のようなデフォルト画面が表示されます。

-
Androidで遅延処理後にメソッドを呼び出す方法【HandlerのpostDelayed活用】
この記事では、Androidアプリにおいて指定した時間の遅延後にメソッドを呼び出す方法を解説します。HandlerクラスのpostDelayed()メソッドを使うことで、数行のコードで簡単に遅延処理を実装できます。手順1:新規プロジェクトを作成するAndroid Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成しましょう。手順2:レイアウトファイル(res/layout/activity_main.xml)以下のコードをres/layout/activity_main.xmlに追加します。画面中央
-
【Android】Googleによるアプリアクティビティの記録をオフにする方法
Googleが自分のサービスとのやり取りを記録していることをご存じでしょうか。検索履歴が保存されていることはよく知られていますが、Android端末の動きまで見られているとは、意外と気づいていない方が多いものです。実はGoogleは、スマートフォン上でどのアプリをいつ使ったかという「アプリアクティビティ」まで記録できるのです。とはいえ、これらの情報が闇に葬られているわけではありません。「マイアクティビティ(My Activity)」ページを使えば、Googleが何を記録しているのかを確認でき、特定の項目については記録しないよう設定することも可能です。アプリの使用履歴を残されたくない場合は、ここ