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
Related
I have a Activity where I load 3 fragments one after another
FragmentA
FragmentB
FragmentC
Flow is Like this I have used Adding fragment one above another
Start-Activity -----> Load FragmentA ----> Load FragmentB ----> Load FragmentC
What I am trying to do now is:
Now assuming now FragmentC is the top fragment shown
I want to find the FragmentA from the stack and just show it instead of creating a fragmentA all over again
Code I have used to add fragmentA is for Example:
Fragment fragment = null;
FragmentTransaction fragmentTransaction = null;
fragment = new FragmentA();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(FragmentA.class.getSimpleName());
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.add(R.id.container, fragment, FragmentA.class.getSimpleName());
if(fragment!=null && fragmentTransaction!=null){
fragmentTransaction.commitAllowingStateLoss();
}
Look at FragmentManager.getBackStackEntryAt method, from there you can go back to any fragment of your history…
Loop through the back stack entries, meanwhile, if you find any matching Fragment by id or tag, just pop back stack inclusive with fragment A's name/tag so that the fragment A is just displayed rather than adding once again.
The example code to retrieve a fragment by Tag would look like this
FragmentA frA = getSupportFragmentManager().findFragmentByTag(FragmentA.class.getSimpleName());
and if it's not null you can reuse it in your container
if(frA != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
//you could add this transactionn to backstack again here if you want to be able to pop it later
fragmentTransaction.add(R.id.container, frA, FragmentA.class.getSimpleName());
} else {
//if your fragment is null as it was destroyed previously you can create a new one here
}
You are giving a tag, fragmentTransaction.addToBackStack(FragmentA.class.getSimpleName()); to the transaction , you can use the same tag to find the fragment in the backstack, before creating a new frgament, check the backstack for the fragment using findFragmentByTag on the fragment manager, if it exist, the method returns the fragment otherwise null
try it!
val fm: FragmentManager? = fragmentManager
for (entry in 0 until fm.getBackStackEntryCount()) {
Log.i(TAG, "Found fragment: " + fm.getBackStackEntryAt(entry).getId())
}
I am pretty new to android development so I am curious how to work properly with Fragments.
My application contains a BottomNavigationActivity which switches between 3 fragments with this code:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_montage_order_detail, fragment).commit();
I am storing the Fragments in a List<Fragment> to avoid loosing the current state. But everytime I replace the fragment with another the method onDestroy() is called.
I know, I know I could add and remove the fragment in the fragmentmanager instead of replacing it. I googled alot and most of the tutorials tell me to replace the fragment.
Whats the common way to keep a fragments state without recreating it on every call?
Find the solution
It will not recreate fragment anytime
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_montage_order_detail, fragment).commit();
Use fragment TAG at time of creation of fragment then when you want to get it again use findFragmentByTag. if fragment already created then old one will be find by fragment manager.
Fragment previousFragment = fragmentManager.findFragmentByTag("TAG");
I suggest you use show,not forreplace
protected void addFragmentStack(Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (this.mContent != fragment) {
if (fragment.isAdded()) {
ft.hide(this.mContent).show(fragment);
} else {
ft.hide(this.mContent).add(getFragmentViewId(), fragment);
}
this.mContent = fragment;
}
ft.commit();
}
Try using switchFragment to switch fragment, it will show fragment if it is already added.
Use fragmentTransaction.show method to re-use existing fragment i.e. saved instance.
public void switchFragment (Fragment oldFragment, Fragment newFragment, int frameId) {
boolean addFragment = true;
FragmentManager fragmentManager = getFragmentManager ();
String tag = newFragment.getArguments ().getString (BaseFragment.TAG);
Fragment fragment = fragmentManager.findFragmentByTag (tag);
// Check if fragment is already added
if (fragment != null && fragment.isAdded ()) {
addFragment = false;
}
// Hide previous fragment
String oldFragmentTag = oldFragment.getArguments ().getString (BaseFragment.TAG);
if (!tag.equals (oldFragmentTag)) {
FragmentTransaction hideTransaction = fragmentManager.beginTransaction ();
Fragment fragment1 = fragmentManager.findFragmentByTag (oldFragmentTag);
hideTransaction.hide (fragment1);
hideTransaction.commit ();
}
// Add new fragment and show it
FragmentTransaction addTransaction = fragmentManager.beginTransaction ();
if (addFragment) {
addTransaction.add (frameId, newFragment, tag);
addTransaction.addToBackStack (tag);
}
else {
newFragment = fragmentManager.findFragmentByTag (tag);
}
addTransaction.show (newFragment);
addTransaction.commit ();
}
Ya, you can also manage the state by managing the backstack.
I have implemented fragments in my application. Here my code for swiching fragment in fragment_container.
private void switchFragment(Fragment fragment, boolean isAddToBackStack, String tag)
{
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, fragment, tag);
if (isAddToBackStack)
ft.addToBackStack(tag);
setCurrentTopFragment(Integer.parseInt(tag));
ft.commit();
}
I have 4 fragments A,B,C and D and for switching between this fragmnets I am using above method. I have A,C,B in my backstack. If again I switch to fragmnet A, my backstack is like A,C,B,A. What I actually want is If I swich to A again I want backstack sequence like this C,B,A. Means Remove old instance from backstack and add new to it.
First get the back-stacked Fragment by id which you need to remove:
Fragment fragment = getSupportFragmentManager().getFragment(new Bundle(), TAG_KEY)
or there are several methods getBackStackEntryCount(), getBackStackEntryAt. After getting the fragment which you need to remove. Remove it from the fragment back-stack.
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(fragment);
Then you can add a new fragment Done :)
I am fetching data from server on fragment "A" call. When i replace "A" with "B", and after coming back to "A" from "B" , fragment "A" is called from everytime, so HTTPGET is made every time . How to avoid this and reuse fragment like REORDER_TO_FRONT in activity?
I am using this code to replace with new fragment
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.rl_fragment_content, newFragment,
backStackName);
transaction.addToBackStack(backStackName);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
And when i backpress ,
Fragment fragment = null;
fragment = getSupportFragmentManager().findFragmentByTag(
"some_fragment_name");
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.rl_fragment_content, fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack("some_fragment_name");
transaction.commit();
Just prevent your fragment from re-inflating the view by using,
if (view != null) {
//this will prevent the fragment from re-inflating(when you come back from B)
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
} else {
//inflate the view and do what you done in onCreateView()
}
There are a few ways to do this, but the easiest would be to use add and hide on the fragment instead of replace. This code (untested) will show newFragment2 and add newFragment1 to the backstack. In your backstack code will show newFragment1 and add whatever you want to the backstack
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.rl_fragment_content, newFragment1,
backStackName1); //now you have an instance of newFragment1
transaction.add(R.id.rl_fragment_content, newFragment2,
backStackName2); //now you have an instance of newFragment2
transaction.addToBackStack(backStackName1);
transaction.show(newFragment2);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
and later
Fragment fragment = null;
fragment = getSupportFragmentManager().findFragmentByTag(
backStackName1);
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.show(fragment)
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack("whatever_you_want");
transaction.commit();
Note this will persist the view. If you want to persist between screen rotations you'll need to implement a Bundle in your host Activity.
Short version:
I have activity with fragment, which include ViewPager (with FragmentStatePagerAdapter) and on resume to this fragment it recreates. How can I by back press return to Fragment and restore is state and it's Viewpager?
Details:
I have an activity with FrameLayout (R.id.themesFragmentsLayout), in activity's method onCreate(..) I do:
if (savedInstanceState == null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ThemesFragment fragment = new ThemesFragment();
fragmentTransaction.replace(R.id.themesFragmentsLayout, fragment, ThemesFragment.TAG);
fragmentTransaction.commit();
}
ThemesFragment include only ViewPager with FragmentStatePagerAdapter, which holds 3 fragments:
public Fragment getItem(int position) {
switch (position) {
case ID_THEME_PAST:
return new ThemePastFragment();
case ID_THEME_OF_DAY:
return new ThemeOfDayFragment();
case ID_THEME_UPCOMING:
return new ThemeUpcomingFragment();
default:
return null;
}
}
In ThemeOfDayFragment for example, user can click some button and I change ThemesFragment (which holds ViewPager) with some another (for example ThemeDetails):
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.addToBackStack(newFragment.getClass().getSimpleName());
fragmentTransaction.replace(((AboutMyStyleApplication) getActivity().getApplication()).getCurrentFragmentsLayoutId(), newFragment, newFragment.getClass().getSimpleName());
fragmentTransaction.commitAllowingStateLoss(); // or fragmentTransaction.commit(); - same result
But when he came back (by back key press for example) ThemesFragment recreates, and all fragments in ViewPager recreates to.
In ThemesFragment I set setRetainInstance(true)
Can anyone help?