Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách truyền dữ liệu giữa hai Fragment trong Android

Giới thiệu

Bài viết hướng dẫn truyền dữ liệu từ Fragment A sang Fragment B thông qua Interface callback trong Activity chứa (Host Activity). Đây là pattern phổ biến trước khi có ViewModel/SharedViewModel.

Kiến trúc

  • MainActivity: Implement interface SendMessage, điều phối ViewPager + TabLayout
  • FragmentOne: Gửi dữ liệu qua interface
  • FragmentTwo: Nhận dữ liệu qua method displayReceivedData()
  • ViewPagerAdapter: Quản lý 2 fragment (code không hiển thị trong nguyên bản nhưng cần thiết)

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Layout chính (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Bước 3: FragmentOne (Gửi dữ liệu)

// FragmentOne.java
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class FragmentOne extends Fragment {
    private SendMessage sendMessage;

    public FragmentOne() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_fragment_one, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button btnPassData = view.findViewById(R.id.btnPassData);
        final EditText inData = view.findViewById(R.id.passMessage);

        btnPassData.setOnClickListener(v -> {
            String message = inData.getText().toString().trim();
            if (sendMessage != null) {
                sendMessage.sendData(message);
            }
        });
    }

    // Interface callback
    interface SendMessage {
        void sendData(String message);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            sendMessage = (SendMessage) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity phải implement SendMessage interface");
        }
    }
}
<!-- fragment_fragment_one.xml -->
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/passMessage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/btnPassData"
            android:layout_margin="16dp"
            android:hint="Nhập nội dung" />

        <Button
            android:id="@+id/btnPassData"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="GỬI DỮ LIỆU SANG FRAGMENT HAI" />
    </RelativeLayout>
</ScrollView>

Bước 4: FragmentTwo (Nhận dữ liệu)

// FragmentTwo.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FragmentTwo extends Fragment {
    private TextView textView;

    public FragmentTwo() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_fragment_two, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        textView = view.findViewById(R.id.txtData);
    }

    // Method được gọi từ MainActivity
    void displayReceivedData(String message) {
        textView.setText("Dữ liệu nhận được: " + message);
    }
}
<!-- fragment_fragment_two.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=".FragmentTwo">

    <TextView
        android:id="@+id/txtData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_centerInParent="true"
        android:text="Chưa nhận dữ liệu" />
</RelativeLayout>

Bước 5: ViewPagerAdapter (Cần bổ sung)

// ViewPagerAdapter.java
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

public class ViewPagerAdapter extends FragmentPagerAdapter {
    public ViewPagerAdapter(@NonNull FragmentManager fm) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0: return new FragmentOne();
            case 1: return new FragmentTwo();
            default: return new FragmentOne();
        }
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return position == 0 ? "Fragment 1" : "Fragment 2";
    }
}

Bước 6: MainActivity (Điều phối)

package app.com.sample;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity implements FragmentOne.SendMessage {
    TabLayout tabLayout;
    ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.viewPager);
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewPagerAdapter);

        tabLayout = findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void sendData(String message) {
        // Tìm FragmentTwo bằng tag tự động của ViewPager
        String tag = "android:switcher:" + R.id.viewPager + ":" + 1;
        FragmentTwo fragmentTwo = (FragmentTwo) getSupportFragmentManager().findFragmentByTag(tag);
        if (fragmentTwo != null) {
            fragmentTwo.displayReceivedData(message);
        }
        // Chuyển sang tab 2 để người dùng thấy kết quả
        viewPager.setCurrentItem(1);
    }
}

Bước 7: Manifest

<?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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhập text ở Fragment 1 → nhấn nút → tự chuyển sang Fragment 2 hiển thị dữ liệu.

Cách truyền dữ liệu giữa hai Fragment trong Android

Cách hiện đại hơn (Khuyến nghị)

Hiện nay nên dùng SharedViewModel (Jetpack ViewModel) để chia sẻ dữ liệu giữa Fragment:

// SharedViewModel.java
public class SharedViewModel extends ViewModel {
    private final MutableLiveData<String> data = new MutableLiveData<>();

    public void setData(String value) { data.setValue(value); }
    public LiveData<String> getData() { return data; }
}

// Trong FragmentOne:
viewModel.setData("Hello");

// Trong FragmentTwo:
viewModel.getData().observe(getViewLifecycleOwner(), textView::setText);

Ưu điểm: Tách biệt logic, tự động xử lý lifecycle, không cần interface callback, dễ test.