Android开发:分属不同Activity的Fragment间如何通信?
Hey there! I totally get where you're stuck—cross-Activity Fragment communication isn't covered as much as sibling Fragments in basic tutorials, but there are solid, practical ways to pull this off. Let's break down the most straightforward approaches tailored for your scenario:
1. Pass Data via Intent (The Most Direct Method)
Since you're moving from Activity A to Activity B, the simplest way is to carry your Fragment A data through the Intent that launches Activity B, then hand it off to Fragment B once Activity B is initialized.
Here's how to do it step-by-step:
- In Fragment A, trigger the Activity launch with data:
// Let's say you've collected data in Fragment A, like a string or custom object val dataToShare = "Hello from Fragment A!" val launchIntent = Intent(requireContext(), ActivityB::class.java) // Put data into the intent—use a unique key to retrieve it later launchIntent.putExtra("FRAGMENT_A_DATA_KEY", dataToShare) startActivity(launchIntent) - In Activity B, receive the data and pass it to Fragment B:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_b) // Grab the data from the incoming intent val receivedData = intent.getStringExtra("FRAGMENT_A_DATA_KEY") // Initialize Fragment B and attach the data via arguments val fragmentB = FragmentB().apply { arguments = Bundle().apply { putString("FRAGMENT_B_DATA_KEY", receivedData) } } // Add Fragment B to the activity's container supportFragmentManager.beginTransaction() .replace(R.id.fragment_container, fragmentB) .commit() } - In Fragment B, retrieve the data:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Pull data from the arguments bundle arguments?.let { bundle -> val data = bundle.getString("FRAGMENT_B_DATA_KEY") // Now you can use this data in Fragment B! } }
2. Use a Shared ViewModel (For Reactive/Real-Time Updates)
If your project uses Jetpack components, a shared ViewModel tied to the Application context is a clean, architecture-friendly option. This works because both Activities can access the same ViewModel instance, letting Fragment A push data and Fragment B observe it.
Steps to implement:
- Create a shared ViewModel:
import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import android.app.Application class SharedDataViewModel(application: Application) : AndroidViewModel(application) { // LiveData to hold the shared data—observers get notified when it changes val sharedContent = MutableLiveData<String>() } - In Fragment A, update the ViewModel data:
val viewModel = ViewModelProvider( requireActivity(), ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application) ).get(SharedDataViewModel::class.java) // Set the data from Fragment A viewModel.sharedContent.value = "Reactive data from Fragment A" - In Fragment B, observe the ViewModel for updates:
val viewModel = ViewModelProvider( requireActivity(), ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application) ).get(SharedDataViewModel::class.java) // Observe the LiveData—this will trigger whenever the data changes viewModel.sharedContent.observe(viewLifecycleOwner) { data -> if (!data.isNullOrEmpty()) { // Use the updated data here } }
Pro tip: Always use viewLifecycleOwner when observing in Fragments to avoid memory leaks when the Fragment is destroyed.
3. Local Storage (For Persistent Data)
If you need the data to stick around even after the app restarts, or if you're passing data across multiple screens beyond just these two Fragments, use local storage options like SharedPreferences or Room Database.
Example with SharedPreferences:
- In Fragment A, save the data:
val prefs = requireContext().getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE) prefs.edit().putString("PERSISTENT_DATA_KEY", "Persistent data from Fragment A").apply() - In Fragment B, retrieve the data:
val prefs = requireContext().getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE) val savedData = prefs.getString("PERSISTENT_DATA_KEY", "") // Use the saved data
Which One Should You Choose?
- Go with the Intent method for one-time data passes when launching Activity B—it's simple and requires no extra setup.
- Use the Shared ViewModel if you need real-time data sync between the two Fragments, or if you're following MVVM architecture.
- Opt for local storage when the data needs to be persisted across app sessions.
Hope this clears up your confusion and gets you back on track!
内容的提问来源于stack exchange,提问作者dodie

