Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Previous fragment visible under the new fragment

I have a tab + ViewPager layout and in one of these tabs I have a list view. When I replace that list fragment upon the onclick I can still see the old fragment under the new fragment. See:

enter image description here

Code:

FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); HallsInStateFragment hallsForState = new HallsInStateFragment();         transaction.replace(R.id.container, hallsForState); transaction.addToBackStack(null); transaction.commit(); 

where the R.id.container is the FrameLayout in the view.

like image 618
SquiresSquire Avatar asked May 20 '13 05:05

SquiresSquire


2 Answers

when need to remove all views from the parent view you need to call removeAllViews() at container in your onCreateView() method of your fragment.

Here is the code:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  container.removeAllViews(); // Inflate the layout for this fragment  return inflater.inflate(R.layout.fragment_example, container, false);  } 
like image 147
taranjeetsapra Avatar answered Sep 28 '22 10:09

taranjeetsapra


Instead of R.id.container put id of fragment like this: ((ViewGroup)getView().getParent()).getId(). Actually it is not replacing the fragment but the previous layout i.e FrameLayout. It works for me and i hope it will work in your case also.

like image 36
varun bhardwaj Avatar answered Sep 28 '22 12:09

varun bhardwaj