Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีเรียกเมธอดของ Activity จาก Fragment ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการให้ Fragment เรียกใช้เมธอดของ Activity ที่เป็นเจ้าของ (Host Activity) ผ่านการ Cast Context

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project แล้วกรอกข้อมูลที่จำเป็น

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ Activity (activity_main.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=".MainActivity">
    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ด Activity (MainActivity.java)

package com.example.fragmenttoactivity;

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);
        
        // เพิ่ม Fragment ลงใน FrameLayout
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout, new SampleFragment()).commit();
    }

    // เมธอดที่ Fragment จะเรียก
    public void fragmentMethod() {
        Toast.makeText(this, "Method called From Fragment", Toast.LENGTH_LONG).show();
    }
}

ขั้นตอนที่ 4: สร้าง Fragment

SampleFragment.java

package com.example.fragmenttoactivity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;

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);
        
        // เรียกเมธอดของ Activity
        ((MainActivity) requireActivity()).fragmentMethod();
        
        return view;
    }
}

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: ตั้งค่า Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.fragmenttoactivity">
    <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>

การทดสอบ

รันแอปพลิเคชันบนอุปกรณ์จริง เมื่อ Fragment โหลด จะเรียกเมธอดของ Activity แสดง Toast ทันที

วิธีเรียกเมธอดของ Activity จาก Fragment ใน Android

แนวทางที่ดีกว่า (Best Practice)

แทนการ Cast โดยตรง ควรใช้ Interface เพื่อลดการผูกมัด (Decoupling):

// Interface
public interface OnFragmentInteractionListener {
    void onFragmentAction();
}

// Activity implements Interface
public class MainActivity extends AppCompatActivity implements OnFragmentInteractionListener {
    @Override
    public void onFragmentAction() {
        // ทำงานที่นี่
    }
}

// Fragment ใช้ Listener
public class SampleFragment extends Fragment {
    private OnFragmentInteractionListener listener;
    
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            listener = (OnFragmentInteractionListener) context;
        }
    }
    
    // เรียกใช้: listener.onFragmentAction();
}