Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Fragment with add() method doesn't hide previous fragments

I'm experiencing "unexpected behaviour" when using add() method to add a new fragment.

I want to add a new fragment on a FrameLayout, but when I do it the previous fragment stills visible.

  • Is this the expected result when using add() method?

  • It is because I am using a FrameLayout and add() method just place a fragment over the FrameLayout without affect the previous one?

Thx

like image 857
Axel M. Garcia Avatar asked Jun 03 '11 14:06

Axel M. Garcia


People also ask

How do you hide a fragment?

Showing and hiding fragment's viewsUse the FragmentTransaction methods show() and hide() to show and hide the view of fragments that have been added to a container.

How do I know if a fragment is already added?

You can use findFragmentByTag() or findFragmentById() functions to get a fragment. If mentioned methods are returning null then that fragment does not exist. Save this answer.

How do you know if a fragment is visible?

In ViewPager2 and ViewPager from version androidx. fragment:fragment:1.1. 0 you can just use onPause and onResume callbacks to determine which fragment is currently visible for the user. onResume callback is called when fragment became visible and onPause when it stops to be visible.


2 Answers

Not a bug. Try replace(..). instead adding to the back stack if required.

EDIT I think that using replace or remove() add() will solve your problem but as you highlight in your related post there is a bug which manifests itself under your particular set of circumstances.

like image 134
PJL Avatar answered Sep 18 '22 00:09

PJL


Other simple thing what you can do is to call

FragmentTransaction t = getFragmentManager.beginTransaction();
t.hide(<your_fragment>);
t.add(<container, <new_fragment>);
..do the rest here..
t.commit();

Let me know if this helps.

like image 21
Photon Avatar answered Sep 21 '22 00:09

Photon