Junior — Middle
How can data be transferred between fragments in an application?
sobes.tech AI
Answer from AI
Data between fragments in Android can be transferred in several ways:
- Via Bundle when creating a fragment — pass data in the fragment's arguments using
setArguments()and retrieve them withgetArguments().
val fragment = MyFragment()
val bundle = Bundle()
bundle.putString("key", "value")
fragment.arguments = bundle
-
Via ViewModel shared between activity and fragments — use
ViewModelto store and exchange data between fragments. -
Via interfaces and callbacks — the fragment calls methods of the activity, which passes data to another fragment.
-
Via SharedPreferences or database — for more permanent storage and exchange.
The most recommended way is to use ViewModel with LiveData for reactive and safe data exchange between fragments.