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

  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. Via ViewModel shared between activity and fragments — use ViewModel to store and exchange data between fragments.

  2. Via interfaces and callbacks — the fragment calls methods of the activity, which passes 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.