Reputation: 11695
I want to use LiveData
in a Fragment
to observe the change of some data. Now let's suppose:
Fragment A
and Fragment B
have their own containers layout in Activity
, which means we will call FragmentTransaction#add()
separately for them and their onPause()
or onResume()
will not be called during adding(UI change) because of no FragmentTransaction#replace()
action.LiveData
observer named as O, it will observe the change of some data, and update UI according to it. The key is: we want to play some animation for the change, instead of just calling properties setter (like TextView#setText()
) naively. For example, maybe the animation is the one played after we called RecyclerView.Adapter#notifyItemInserted()
After adding B, A is considered as invisible to users. However, both the lifecycle of Fragment A
or of its View
by calling getViewLifecycleOwner()
is still on STARTED
and RESUMED
state. As a result, the animation will play after the data changes observed by O but users cannot see it from the beginning.
How can we solve this problem? Any ideas or answers are appreciated. Thanks in advance.
Upvotes: 5
Views: 2274
Reputation: 13668
If you are adding B (which consumes the space supposedly alloted for A), it is better to also remove fragment A. You get multiple benefits for this:
1) You solve your problem. (Thats if youre using viewLifeCycleOwner
in observing your LiveData
)
2) You decrease memory consumption of your app, since the Fragment A's view will be torn down.
This is
which means we will call FragmentTransaction#add() separately
is also not a problem. Note that you can chain FragmentTransaction
s such as:
supportFragmentManager.beginTransaction()
.replace(view1.id, fragmentB)
.remove(fragmentA)
.commit()
Upvotes: 2