Fragments inside ViewPager are not destroyed - android

In my MainActivity in onCreate method I add() MainFragment to FrameLayout main_view_container:
if (savedInstanceState == null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_view_container, new MainFragment(), MainFragment.FRAGMENT_TAG);
fragmentTransaction.commit();
}
In my MainFragment I have ViewPager with FragmentStatePagerAdapter and every page is Fragment itself (PagerFragment).
Then at some point after button click I want to replace whole MainFragment with another Fragment (ReplacementFragment) and add transaction to back stack so I can go back to MainFragment on back button pressed. So I do the following:
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_view_container, new ReplacementFragment(), null);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
After I commit transaction MainFragment is stopped and onDestroyView() is called but completely nothing happens with PagerFragments (that are in ViewPager in MainFragment) Not event a single onStop() call. Then when I go back MainFragment's View is recreated in onCreateView() which means new Instance of ViewPager as well, but still nothing with PagerFragments.
How is that possible that in parent Fragment onDestroyView is called but not in children Fragments?

You must use getChildFragmentManager() when creating pager adapter inside MainFragment.

Related

Android Back to previous fragment by popBackStack

I have 3 fragments: Home, A and B. Home and A are in mobile navigation menu.
User goes from A to B and then press back button. The issue that if I use getFragmentManager().popBackStack(); onCreateView of fragment A is calling and I have duplicating of content.
But if I use getActivity().onBackPressed(); it goes to Home fragment instead of A.
How to display fragment A by clicking back button without refreshing the view?
Here is how I make transaction from A to B
CertificateItemFragment certificateItemFragment = new CertificateItemFragment(item);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, certificateItemFragment).addToBackStack(null);
fragmentTransaction.commit();
You need to know some premise before using FragmentManager.
in Activity there is FragmentManager and we should call it with getSupportFragmentManager(), getFragmentManager() is deprecated.
in Fragment there are multiple FragmentManagers called ParentFragmentManager and ChildFragmentManager, the final FragmentManager which is deprecated too. And ParentFragmentManager will be same as Activity's FragmentManager
getActivity().onBackPressed() will pull out fragment if any stack exists in Activity's FragmentManager
fragmentManager.popBackStack() will pull out fragment if any stack exists in Activity's or Fragment's FragmentManager rely on who calls
Base on above points
(1) If You want to hold fragments in Activity, you should call getSupportFragmentManager() in Activity, and call getParentManager() in Fragment, then onBackPressed() will pull out the fragment you last add to stack.
(2) If you want to hold fragments in a Fragment and Separated from Activity, you should call getChildFragmentManager() in Fragment, then activity.onBackPressed() will pull out the fragment which in Activity's fragment stack and ignore other fragments in Fragment's fragment stack.
For question will be same as case (1), and if you dont want re-create fragment, you should use add() instead of replace()
in Fragment A
CertificateItemFragment certificateItemFragment = new CertificateItemFragment(item);
FragmentManager fragmentManager = getParentFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.nav_host_fragment, certificateItemFragment).addToBackStack(CertificateItemFragment.TAG);
fragmentTransaction.commit();
now onBackPressed() will backstack from CertificateItemFragment to Pre-Fragment
In normal case navigation item list menu open fragment which are replace to each other but when we move inside of any item as like in your case move from fragment A to B,
In this case normally we use another activity on which create fragment.
If you do't want to use activity then, you just need to add fragment.
try below code that may help you
CertificateItemFragment certificateItemFragment = new CertificateItemFragment(item);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.nav_host_fragment, certificateItemFragment).addToBackStack(CertificateItemFragment.TAG);
fragmentTransaction.commit();

FragmentManager in RecyclerView adapter

I have an activity with a viewpager that contains 2 tabs. Each tab is a host fragment that has 2 child fragments. First fragments are recyclerviews that open up other fragments with FragmentTransactions. I am having trouble creating different backstacks for them.
So in my recyclerview adapter in onBindViewHolder i have the onclicklistener like this:
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirstFragment fragment1 = new FirstFragment();
SecondFragment fragment2 = new SecondFragment();
FragmentManager fm = ((FragmentActivity) view.getContext()).getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction
.replace(R.id.frame_container, fragment2,"Tag")
.addToBackStack(null)
.commit();
}
});
If i make the transaction like this from the recyclerview, the backstack is the same for both tabs, so if i open second fragments on tab1, then on tab2, if i go back to tab1 and press back, the second fragment on tab2 gets popped insead.
If i make a button in the FirstFragment outside of the recyclerview and make the fragment transaction from FirstFragment like this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, SecondFragment.newInstance(), "Tag");
ft.addToBackStack(null);
ft.commit();
}
});
then it works as intended, but i want to do it from the recyclerview.
Is there any way this can be done?
You should carry your item click listener logic into the host fragment of the tab. Then in both of your host fragments you should make required transaction by using child fragment manager. Thus, the transactions are kept in the back stack of the host fragments. Then you have to manage these different stacks which are activity's fragment stack, host1's fragment stack and host2's fragment stack. For that purpose, you have to override onBackPressed in your activity then you ask the current visible host fragment for if there is a transaction. If there is you should pop that transaction and return in onBackPressed callback.If there is no let the activity to handle event by calling super.

Fragment not showing previous data when coming from another fragment

In my android activity I am using multiple fragments, I am successfully switching these fragments according to my requirement but problem is that when I am switching Fragment 1 to Fragment 2 and back from Fragment 2 to Fragment 1, Fragment 1 not showing previous data Fragment 1 start from stretch, but I want to show previous data same as I was selected.
Here is my code for go Fragment 1 (fragment_search_customerProfile) to Fragment 2 (fragment_CustomerInfo):
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, new fragment_Search());
FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.cpFrame);
layout.removeAllViewsInLayout();
transaction.remove(new fragment_search_customerProfile()).commit();
Here is my code for back Fragment 1 (fragment_search_customerProfile) fromFragment 2 (fragment_CustomerInfo):
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Log.d("fragment_Search", fromSearch + "");
transaction.replace(R.id.custIndoFram, new fragment_search_customerProfile());
FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.custIndoFram);
layout.removeAllViewsInLayout();
transaction.remove(new fragment_CustomerInfo()).commit();
Can anyone explain me how can I stay save my fragment data?
Instead of transaction.replace(R.id.filterFram, new fragment_Search());
you can use transaction.add to add fragment while having the data of first one
transaction.add(R.id.filterFram, new fragment_Search());
transaction.addToBackStack(null);
From fragment two you can use .show instead of replace to show the first fragment
and hide fragment two from the first one. transaction.show(getSupportFragmentManager().findFragmentByTag("firstFragmentTag")).commit();
You can simple keep the instances of the fragments, so in your Activity you would have fields like that.
private Fragment fragment1;
private Fragment fragment2;
And now you can use the sexy replace() option,
To add Fragment1
if (fragment1 == null) {
fragment1 = new fragment_Search();
}
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, fragment1);
and same for Fragment2
And you can hold the state of the fragment (data it retrieves) in the Fragment itself, and in your onViewCreated() you check, if the state is not null, you update the view immediately.
class Fragment1 extends Fragment {
private State state;
public void onViewCreated(View v) {
if (state != null) {
// Update UI here
}
}
}
UPDATE
Using your own code
private Fragment fragment1; // This is a field outside of below method
if (fragment1 == null) {
fragment1 = new fragment_Search();
}
FragmentManager manager = getChildFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, fragment1).commit();
FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.cpFrame);
layout.removeAllViewsInLayout();
Going to fragment2 should be the same, and this code is used to go to Fragment1 and Fragment2, doesn't matter if you are going back or first time.
You have to add fragment instead of remove or replace

Unable to remove Nested fragment completely from Main Fragment

In my activity, I have various fragments. By default activity displays a map. On listitem click, fragment A, B or C is displayed using following code:
protected void replaceFragment(int i) {
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
switch (i) {
case FRAGMENT_A:
aFragment = new AFragment ();
fragmentTransaction.replace(R.id.main_framelayout_replace,
aFragment , TAG_A_FRAGMENT);
fragmentTransaction.commit();
break;//and so on.....
default:
break;
}
}
Here I'm facing an issue: When I replace FragA with FragB which is nested fragment i.e. it contains list and detail fragment within itself. When I try to remove any fragment other than FragB, I'm able to do it successfully and show the default map screen but when I'm on FragB and try to remove it, I'm not able to see default map screen. Instead a blank white screen is getting displayed.
Removing of fragments is done as follows:
if (aFragment != null) {
fragmentManager.beginTransaction()
.remove(aFragment ).commit();
}//and so on...
For FragB which is having list and detailed fragment, I also do following in onDetach of FragB,
fragmentManager.beginTransaction()
.remove(MainActivity.listFragment).commit();
Am I doing anything wrong here? Any help appreciated.
Note: I'm not getting any exception in any try catch. All the lines of code are getting executed without error including onDetach of FragB.
In your FragB class (which extends Fragment) you should be using ChildFragmentManager to manage nested fragments.

Removing a Fragment from the back stack

I have a 3 fragments in an activity when the a tablet is held in portrait. However I only have 2 of these fragments when in landscape. The problem I am having is when going from portrait to landscape the activity is creating the 3rd fragment. I receive and error as this fragment cannot be created.
I have worked out that this fragment is being created because it is in the back stack.
I have tried to remove the fragment in the onDestroy method by using
FragmentTransaction f = fragmentManager.beginTransaction();
f.remove(mf);
f.commit();
However the I get an error saying that I cannot use this function after the onSaveInstanceState
What would be the correct way of taking this fragment out of the back stack?
Update
I should probably add that the fragment I am having problems with is a mapFragment from this libary
https://github.com/petedoyle/android-support-v4-googlemaps
The way I use it is like so
mf = MapFragment.newInstance(1, true);
ft = fragmentManager.beginTransaction();
ft.replace(R.id.mapContainer, mf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack("map");
ft.commit();
You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods:
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();
I created a code to jump to the desired back stack index, it worked fine to my purpose.
ie. I have Fragment1, Fragment2 and Fragment3, I want to jump from Fragment3 to Fragment1
I created a method called onBackPressed in Fragment3 that jumps to Fragment1
Fragment3:
public void onBackPressed() {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-2).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
In the activity, I need to know if my current fragment is the Fragment3, so I call the onBackPressed of my fragment instead calling super
FragmentActivity:
#Override
public void onBackPressed() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.my_fragment_container);
if (f instanceof Fragment3)
{
((Fragment3)f).onBackPressed();
} else {
super.onBackPressed();
}
}
you show fragment in a container (with id= fragmentcontainer) so you remove fragment with:
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer);
fragmentTransaction.remove(fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
In case you ended up here trying to figure out how to remove fragment(s) from backstack and you are using Android Jetpack Navigation component you could just use app:popUpTo and app:popUpToInclusive in action node of navigation graph xml to specify fragments that you want to pop out of back stack.
https://developer.android.com/guide/navigation/navigation-navigate#pop
Check this too
https://stackoverflow.com/a/51974492/4594986
What happens if the fragment that you want to remove is not on top of the stack?
Then you can use theses functions
popBackStack(int arg0, int arg1);
popBackStack(String arg0, int arg1);

Categories

Resources