2

I've implemented something like the below picture:

enter image description here

I have some Tabs and every tab may have some buttons which load some different fragments. In this situation, in Tab 1, Button 1 loads Fragment 1, and Button 2 loads Fragment 2 and each time the Fragments will be re-created. but I want Buttons to load Fragments just once and avoid re-creating next times.

Button 1 current onClick:

FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_root, FragmentOne.newInstance(),"Frag1");
transaction.commit();

How can I save fragments states to avoid reloading every time?


EDIT

The Tab 1 and Tab 2 Fragments are inside a ViewPager so I could not use ViewPager for Fragment 1 and Fragment 2.

3
  • you can create a view pager without tabs Commented May 20, 2019 at 8:31
  • inthecheesefactory.com/blog/… Commented May 20, 2019 at 8:43
  • @AravindV the root fragment that contains Button 1 and Button 2 is inside ViewPager. I don't want to implement a ViewPager inside another ViewPager. Commented May 20, 2019 at 9:08

2 Answers 2

0

Use below code

FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container_root, FragmentOne.newInstance(),"Frag1");
transaction.addToBackStack("Frag1");
transaction.commit();

instead of

FragmentTransaction transaction = 
getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_root, FragmentOne.newInstance(),"Frag1");
transaction.commit();

Problem:

You are trying to replace fragment while adding them via FragmentTransaction. If you need to keep instance of them you need to use transaction.add method.

Caution:

Using this method can overlap fragments. So you need to add backgroundcolor to both fragments and make the parent layout as clickable so that you can interact

Sign up to request clarification or add additional context in comments.

Comments

0

you can create your tabs with viewpager

ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setOffscreenPageLimit(tabsNumber - 1); // e.g. send 2 as parameter for 3 tabs

and save your tab state

3 Comments

I used ViewPager to implement my tabs but the root fragment that contains Button 1 and Button 2 is inside ViewPager. I don't want to implement a ViewPager inside another ViewPager.
when you use viewpager page limit your tab not getting re create so wich Fragment was present in tab 2 remains present
I think you did not pay enough attention to the picture I shared. Two different fragments inside Tab 1 made the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.