FragmentTransaction add() behavior

烈酒焚心 提交于 2019-12-12 04:54:35

问题


Working with fragments I've always used replace() for my transactions, but I wish I didn't have to save instance states anymore to restore a fragment's view and prevent reloading when coming back to that fragment. So, I've decided to work with add(). The thing is when I add another fragment, the previous fragment view remains in the background and that's fine (that's the behavior I expected), but the problem is I can actually interact with the views in the background. Example:

Fragment A has a Button

Fragment B has a TextView

When I add Fragment A and later add Fragment B, I'm able to click on Fragment A's Button, even staying on Fragment B's view.

I'm using:

FragmentTransaction fragmentTransaction = 
            getSupportFragmentManager().beginTransaction().
            add(getRootViewContainer(),fragment,fragment.getClass().getSimpleName());

if (shouldGoBack) 
    fragmentTransaction.addToBackStack(fragment.getClass().getSimpleName());

where getRootViewContainer() returns the id of the FrameLayout I'm using as my activity main container.

Now, is it really the default behavior of add()?

If so, is there a proper way to avoid this or one just has to use replace()?


回答1:


FragmentTransaction.hide(fragmentBehind); //works for me!

example :

//I have it globally available
FragmentTransaction trans = MainActivity.getManager().beginTransaction(); 

//not globally 
FragmentTransaction trans = getFragmentManager().beginTransaction();
MapFragment newFragment = new newFragment();
trans.add(R.id.fragmentContainer, newFragment, tag);
trans.hide(this);
trans.addToBackStack(tag);
trans.commit();



回答2:


What you can do here is just hide previous fragment at the time of transaction of current fragment.

 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  Fragment newFragment= new MyFragment ();
  ft.hide(CurrentFragment.this);
  ft.show(newFragment);
  ft.commit();

It worked for me just try it.




回答3:


Yes, this is a default behaviour of add(). If you really don't want to user replace(), you can try to disable views which are inside "old" fragment.



来源:https://stackoverflow.com/questions/27924725/fragmenttransaction-add-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!