How data is passed between activity and fragment?

There are multiple ways to pass data between Activity and Fragment. Here are some commonly used methods:

  1. Using Bundle: Data can be passed to a Fragment in an Activity through the use of a Bundle object. The data can be passed to the Fragment using the setArguments() method, and then retrieved in the Fragment using the getArguments() method.
  2. By using interface callback: you can define an interface in a Fragment, have the Activity implement this interface, and then call the interface method in the Activity to pass data to the Fragment.
  3. Using Intents: You can pass data to a Fragment when starting it from an Activity using an Intent. Use the putExtra() method to store data in the Intent, and then retrieve the data in the Fragment using the getArguments() method.
  4. ViewModel allows for sharing data between Activity and Fragment. It is a lifecycle-aware component that ensures data consistency when shared between Activity and Fragment.

These methods can effectively pass data between Activity and Fragment, the choice of which method to use depends on the specific needs and situations.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds