Junior — Middle
Kuidas saab rakenduses andmeid fragmentide vahel edastada?
sobes.tech AI
Vastus AI-lt
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
-
Using ViewModel, shared between activity and fragments — use
ViewModelto store and exchange data between fragments. -
Through interfaces and callbacks — the fragment calls activity methods, which pass 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.