Sobes.tech
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:

  1. Via Bundle when creating a fragment — pass data in the fragment's arguments using setArguments() and retrieve them with getArguments().
val fragment = MyFragment()
val bundle = Bundle()
bundle.putString("key", "value")
fragment.arguments = bundle
  1. Using ViewModel, shared between activity and fragments — use ViewModel to store and exchange data between fragments.

  2. Through interfaces and callbacks — the fragment calls activity methods, which pass data to another fragment.

  3. 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.