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

Kotlinを使ってAndroidアプリのフラグメントからアクティビティのメソッドを呼び出す方法

このチュートリアルでは、Kotlinを使用したAndroidアプリにおいて、フラグメント(Fragment)からアクティビティ(Activity)のメソッドを呼び出す方法を、実際のサンプルコードとともに段階的に解説します。

フラグメントは単体では動作せず必ずアクティビティに依存するため、activity プロパティを介して親アクティビティを取得し、キャストすることでメソッドを呼び出せるようになります。それでは、具体的な手順を見ていきましょう。

ステップ1: 新しいプロジェクトを作成する

Android Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目(プロジェクト名、パッケージ名、保存場所など)をすべて入力してください。テンプレートは「Empty Activity」を選択しておくとスムーズです。

ステップ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">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />
    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

ステップ3: MainActivity.kt を実装する

src/MainActivity.kt に以下のコードを追加します。supportFragmentManager を使って SampleFragment を FrameLayout に表示し、フラグメントから呼び出される fragmentMethod() を定義しています。このメソッドが実行されると、トーストでメッセージが表示されます。

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.frameLayout, SampleFragment()).commit()
    }
    fun fragmentMethod() {
        Toast.makeText(this@MainActivity, "Method called From Fragment",
        Toast.LENGTH_LONG).show()
    }
}

ステップ4: フラグメントを作成する

次に、新しいフラグメントを作成し、レイアウトファイルとKotlinファイルにそれぞれ以下のコードを追加します。

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:layout_centerInParent="true"
        android:text="Calling a simple method from Fragment"
        android:textAlignment="center"
        android:textColor="@android:color/background_dark"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

SampleFragment.kt

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
class SampleFragment : Fragment() {
    override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
    ): View? {
        val view: View = inflater.inflate(R.layout.fragment_sample, container, false)
        (activity as MainActivity?)!!.fragmentMethod()
        return view
    }
}

ここが最も重要な部分です。(activity as MainActivity?)!!.fragmentMethod() のように、activity プロパティで取得した親アクティビティを MainActivity 型にキャストすることで、アクティビティ側の public なメソッドを直接呼び出すことができます。

なお、より安全で保守性の高い実装としては、インターフェースや ViewModel を介した連携も推奨されています。まずは本記事のような基本的な方法を理解したうえで、応用として検討してみるとよいでしょう。

ステップ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.q11">
    <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)アイコンKotlinを使ってAndroidアプリのフラグメントからアクティビティのメソッドを呼び出す方法をクリックします。表示された選択肢から接続済みのモバイルデバイスを選択してください。

アプリが起動すると、フラグメントのビューが表示され、同時にアクティビティの fragmentMethod() が呼び出され、「Method called From Fragment」というトーストメッセージが画面に表示されます。

Kotlinを使ってAndroidアプリのフラグメントからアクティビティのメソッドを呼び出す方法


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

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

  2. Androidアプリでフラグメントからアクティビティのメソッドを呼び出す方法【サンプルコード付き】

    このチュートリアルでは、Androidアプリにおいてフラグメントからアクティビティのメソッドを呼び出す実装方法を解説します。フラグメントは単体では動作せず、必ずアクティビティ上に存在するため、getActivity()で親アクティビティの参照を取得し、適切な型にキャストすることで、アクティビティのpublicメソッドを直接呼び出すことができます。 実装手順 ステップ1:新規プロジェクトの作成 Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。 ステップ2:activ