I switched part of my App from Activities to Fragments so that I can use the neat ActionBar tabs.
However, after completing the transition I ran into an issue: whenever I switch to another tab, that Fragment gets created all over again. Both onCreate and onCreateView get called every time I get to a tab.
I have 4 tabs, each of which is meant to open one of these fragments:
Fragment ShopFragment = new WebActivity();
Fragment SearchFragment = new SearchActivity(context);
Fragment StoreFragment = new StoreLocatorActivity(context, this);
Fragment BlogsFragment = new BlogsActivity(context, this);
Here's my code for the listener:
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
ft.hide(fragment);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
Could someone please point me in the right direction?
When you call FragmentTransaction.replace(...), Android will effectively perform a sequence of FragmentTransaction.remove(...) (for all Fragments currently added to that container) and FragmentTransaction.add(...) (for your supplied Fragment). Removing a Fragment from the FragmentManager will cause the Fragment to be destroyed and its state will no longer be managed. Most noticeably, when you re-add the Fragment all of the views will have been reset. Note: since you are reusing the same Fragment instance, the Fragment will still keep the value any instance variables.
One solution to this problem would be to use FragmentTransaction.detach(Fragment) and FragmentTransaction.attach(Fragment) when switching. This will cause the Fragment views to be recreated (onDestroyView() & onCreateView() will be called), but the instance state bundle will be saved and given back to you between calls and so the view state can be maintained. This is the approach taken by FragmentPagerAdapter when it tries to switch between Fragments.
Alternatively, you could allow the Fragments to be destroyed, but maintain their saved state for them independently. This would use less memory, at the expense of a slower switching time. Methods of note would be FragmentManager.saveFragmentInstanceState(Fragment) and FragmentManager.setInitialSavedState(Fragment.SavedState), in conjuction with adding/removing. This is the approach taken by FragmentStatePagerAdapter.
You can have a look at the source for FragmentPagerAdapter and the source for FragmentStatePagerAdapter for implementation hints.
There is the show/hide option just so the fragments would not need to be repainted/recreated and the onCreate() and onCreateView() won't be reinvoked.
Related
OK I found out that I am opening/replacing the fragment in another layout element than the one the tablayout is in. Therefore the underlying fragment is never really left if i understand correctly and also no lifecycle methods are triggered.
I have FragmentA inside a TabLayout from which i call:
//inside FragmentA
#Override
public void onClickView() {
activity.replaceFragment(FragmentB.newInstance(), true);
}
in replaceFragment the passed fragment is added to the backstack in the transaction and then replaces the fragment
public void replaceFragment(Fragment fragment, boolean doAddToBackStack) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (doAddToBackStack) {
String tag = fragment.getClass().toString();
ft.addToBackStack(tag);
}
ft.replace(R.id.mainFragment, fragment);
ft.commit();
}
After that, FragmentB opens, I do my stuff and return via popBackStackImmediate() to FragmentA:
//inside FragmentB
#Override
public void onClickBack() {
activity.getSupportFragmentManager().popBackStackImmediate();
}
and when I go back I need to update something in FragmentA.
According to another post on the platform when returning to a fragment onCreateView() should be called but that does not work for me. According to the fragment lifecycle documentation the onCreateView() is only called the first time the UI is drawn which would explain my troubles.
My question is now what lifecycle method can I use or what other approach should I take to execute code when returning to a fragment from backstack?
According to the following answer you can add a listener to check when it is being called
https://stackoverflow.com/a/52646588/6468214
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
// Your Code Here
}
});
So basically what I'm working on is very similar to Instagram application, where there're a number of tabs and users can switch to any tab without any delay no matter what there's anything going on, such as refreshing, reloading, and etc. It also uses back button to go back to the previous preserved tab.
In order to achieve this, I've used FragmentManager with FragmentTransaction to show and hide each fragment which represents each tab. I didn't use replace or attach / detach because they destroy view hierarchy of previous tab.
My implementation works pretty well except that showing and hiding fragments are not committed (I highly doubt that this is a right word to say but so far that's how I understood the flow.), or don't occur immediately when SwipeRefreshLayout is refreshing on the fragment (to be hidden) which was added to FragmentManager later than the one to show.
My implementation follows the rules like these. Let's say we have 4 tabs and my MainActivity is showing the first tab, say FirstFragment, and the user selects the second tab, SecondFragment. Because SecondFragment had never been added before, I add it to FragmentManager by using FragmentTransaction.add and hide FirstFragment by using FragmentTransaction.hide. If the user selects the first tab again, because FirstFragment was previously added to FragmentManager, it doesn't add but only show FirstFragment and just hide SecondFragment. And selecting between these two tabs works smoothly.
But when the user "refreshes" SecondFragment's SwipeRefreshLayout and selects the first tab, FragmentTransaction waits for SecondFragment's refresh to be finished and commits(?) the actual transaction. The strange thing is that the transaction is committed immediately the other way around, from FirstFragment's refresh to SecondFragment.
Because this occurs by the order of addition to FragmentManager, I doubt that the order of addition somehow affects backstack of fragments and there might exists something like UI thread priority so that it forces the fragment transaction to be taken place after later-added fragment's UI transition finishes. But I just don't have enough clues to solve the issue. I've tried attach / detach and backstack thing on FragmentTransaction but couldn't solve the issue. I've tried both FragmentTransaction.commit and FragmentTransaction.commitAllowingStateLoss but neither solved the issue.
These are my MainActivity's sample code.
private ArrayList<Integer> mFragmentsStack; // This is simple psuedo-stack which only stores
// the order of fragments stack to collaborate
// when back button is pressed.
private ArrayList<Fragment> mFragmentsList;
#Override
protected void onCreate() {
mFragmentsStack = new ArrayList<>();
mFragmentsList = new ArrayList<>();
mFragmentsList.add(FirstFragment.newInstance());
mFragmentsList.add(SecondFragment.newInstance());
mFragmentsList.add(ThirdFragment.newInstance());
mFragmentsList.add(FourthFragment.newInstance());
mMainTab = (MainTab) findViewById(R.id.main_tab);
mMainTab.setOnMainTabClickListener(this);
int currentTab = DEFAULT_TAB;
mFragmentsStack.add(currentTab);
getSupportFragmentManager().beginTransaction().add(R.id.main_frame_layout,
mFragmentsList.get(currentTab), String.valueOf(currentTab)).commit();
mMainTab.setCurrentTab(currentTab);
}
// This is custom interface.
#Override
public void onTabClick(int oldPosition, int newPosition) {
if (oldPosition != newPosition) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
// First hide the old tab.
fragmentTransaction.hide(mFragmentsList.get(oldPosition));
// Recalculate the fragment stack.
if (mFragmentsStack.contains(newPosition)) {
mFragmentsStack.remove((Integer) newPosition);
}
mFragmentsStack.add(newPosition);
// Add new fragment if it's not added before, or show new fragment which was already hidden.
Fragment fragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(newPosition));
if (fragment != null) {
fragmentTransaction.show(fragment);
} else {
fragmentTransaction.add(R.id.main_frame_layout, mFragmentsList.get(newPosition),
String.valueOf(newPosition));
}
// Commit the transaction.
fragmentTransaction.commitAllowingStateLoss();
}
}
// It mimics the tab behavior of Instagram Android application.
#Override
public void onBackPressed() {
// If there's only one fragment on stack, super.onBackPressed.
// If it's not, then hide the current fragment and show the previous fragment.
int lastIndexOfFragmentsStack = mFragmentsStack.size() - 1;
if (lastIndexOfFragmentsStack - 1 >= 0) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.hide(mFragmentsList.get(mFragmentsStack.get(lastIndexOfFragmentsStack)));
fragmentTransaction.show(mFragmentsList.get(mFragmentsStack.get(lastIndexOfFragmentsStack - 1)));
fragmentTransaction.commitAllowingStateLoss();
mMainTab.setCurrentTab(mFragmentsStack.get(lastIndexOfFragmentsStack - 1));
mFragmentsStack.remove(lastIndexOfFragmentsStack);
} else {
super.onBackPressed();
}
}
Just faced the same issue with only difference - I'm switching fragments on toolbar buttons click.
I've managed to get rid of overlapping fragments overriding onHiddenChanged:
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
yourSwipeRefreshLayout.setRefreshing(false);
}
}
Related Question.
I put together a simple app that goes like this:
Activity -> FirstFragment
Activity: onCreate() -> createFirstFragment()
FirstFragment firstFragment = (FirstFragment) getSupportFragmentManager().findFragmentByTag(FirstFragment.TAG);
if (firstFragment == null)
{
firstFragment = FirstFragment.newInstance();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.firstFragmentContainer, firstFragment, FirstFragment.TAG)
.hide(firstFragment)
//.addToBackStack(null)
.commit();
}
Plain and simple, during onCreate() add and hide a fragment so that I can do show/hide animations later.
Now, my question is this: why does the Activity/FragmentManager not remember this transaction (regardless of whether I .addToBackStack() or setRetainInstance(true) on the fragment) when the activity is killed and recreated? You can test this by checking the Do not keep activities developer option. Start the app, firstFragment is hidden as expected, minimize and come back, and viola! firstFragment is there for all the world to see!
I would expect that this sort of thing would be managed by Android, or do I need to specifically record all my transactions and repeat them when the app is recreated?
Any help/advice would be greatly appreciated!
Edit: Also see related logged bug
Use FragmentStatePagerAdapter like below in your main activity. This internally calls 'onSaveInstanceState' of the fragments and hence keeps the track of the changes you made and retains the transactional states
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// your code here
}
#Override
public int getCount() {
// returns no. of fragments count. in my case it is 4
return 4;
}
onCreate() in mainactivity generally looks like this:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView (R.layout.scrollabletabs_main);
viewPager = (ViewPager) findViewById (R.id.pager);
FragmentManager fragManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragManager));
}
From
http://developer.android.com/training/basics/fragments/fragment-ui.html it is mentioned that,
Note: When you remove or replace a fragment and add the transaction to the back stack, the fragment that is removed is stopped (not destroyed). If the user navigates back to restore the fragment, it restarts. If you do not add the transaction to the back stack, then the fragment is destroyed when removed or replaced.
I am working in an application in which I have used the Sherlock Fragment API.
I am having 6 SherlockFragments for making 6 different screens. Now when my application is launched, initially the onResume for all the fragments are called at once.
I am in a need of a method like in activity we use onResume for moving from one Fragment to another Fragment. I have to call a web service method when I move from one fragment to another fragment.
I tried to use the onResume here, but when I move from 1st to 2nd fragment, then the onResume of the 3rd fragment is called. Alternate fragment is called when we move from one fragment to then next.
Please suggest me, which method should I use to call my web service when I move from 1 fragment to next fragment.
EDITED:
My actual requirement is to have an event which is called when we a Fragment is visible to user. At that event I have to call service for getting updated data.
The onResume method is tied to the Activity. If you're moving back and forth between Fragments attached to a common Activity, onResume won't be called again. However, if you were to press back or navigate away from this Activity and then come back, onResume would be called.
You might consider onAttach.
You can use this way for fix this issue. Actually I was also facing same problem in my application. I was using FragmentPagerAdapter for show multiple tab in ViewPager. I have just hide and show fragment on TabSelection with notifyDataChanged() method for refresh adapter.
My code:
/** Creating an instance of FragmentPagerAdapter */
final MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(fm);
/** Setting the FragmentPagerAdapter object to the viewPager object */
_mPager.setAdapter(fragmentPagerAdapter);
_mActionBar.setDisplayShowTitleEnabled(false);
/** Defining tab listener */
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.hide(fragmentPagerAdapter.getItem(tab.getPosition()));
fragmentPagerAdapter.notifyDataSetChanged();
_mPager.setAdapter(fragmentPagerAdapter);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
_mPager.setCurrentItem(tab.getPosition());
ft.show(fragmentPagerAdapter.getItem(tab.getPosition()));
fragmentPagerAdapter.notifyDataSetChanged();
_mPager.setAdapter(fragmentPagerAdapter);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
};
This is worked for me.
I've used onStart() rather than using onresume() in sherlockfragmentactivity.
And I called to the notifyondatasetchanged.
I have an app with three tabs (ActionBar Tabs), each one with one fragment at a time.
TabListener
TabsActivity
Tab1 -> ListFragment1 -> ListFragment2 -> Fragment3
Tab2 -> Tab2Fragment
Tab3 -> Tab3Fragment
The problem is when I create the FragmentTransaction (inside OnListItemClicked) from ListFragment1 to ListFragment2, the fragments inside the other tabs also change to ListFragment2.
In the end, I want to change fragments only inside on tab and preserve the state of the other tabs.
I'm already saving the state (OnSavedInstance()).
Do you know what I'm missing here?
Some of the code:
public class TabsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
// setup Action Bar for tabs
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// instantiate fragment for the tab
Fragment networksFragment = new NetworksFragment();
// add a new tab and set its title text and tab listener
actionBar.addTab(actionBar.newTab().setText("Tab1")
.setTabListener(new TabsListener(ListFragment1)));
// instantiate fragment for the tab
Fragment historyFragment = new HistoryFragment();
// add a new tab and set its title text and tab listener
actionBar.addTab(actionBar.newTab().setText("Tab2")
.setTabListener(new TabsListener(Tab2Fragment)));
// instantiate fragment for the tab
Fragment settingsFragment = new SettingsFragment();
// add a new tab and set its title text and tab listener
actionBar.addTab(actionBar.newTab().setText("Tab3")
.setTabListener(new TabsListener(Tab3Fragment)));
}
}
public class TabsListener implements ActionBar.TabListener {
private Fragment frag;
// Called to create an instance of the listener when adding a new tab
public TabsListener(Fragment networksFragment) {
frag = networksFragment;
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.fragment_container, frag, null);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(frag);
}
}
public class ListFragment1 extends ListFragment {
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
getListView().setItemChecked(position, true);
ListFragment2 fragment2 = ListFragment2.newInstance(position);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, fragment2);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
}
You're not missing anything (or I'm missing it too).
I searched long and hard for a way to do this "properly" but I couldn't find anything. What I ended up doing is writing my own backstack logic.
Unfortunately my employer owns my code so I can't share any of that verbatim, but here was my approach:
Create an enum with one entry for each of your tabs. Let's call it TabType.
Now create an instance variable tabStacks of type HashMap<TabType, Stack<String>>. Now you can instantiate one stack for each tab - each stack is a list of tags, as specified by Fragment.getTag(). This way you don't have to worry about storing references to Fragments and whether they're going to disappear on you when you rotate the device. Any time you need a reference to a Fragment, grab the right tag off the stack and use FragmentManager.findFragmentByTag().
Now whenever you want to push a Fragment onto a tab, generate a new tag (I used UUID.randomUUID().toString()) and use it in your call to FragmentTransaction.add(). Then push the tag on top of the stack for the currently displayed tab.
Be careful: when you want to push a new fragment on top of an old one, don't remove() the old one, since the FragmentManager will consider it gone and it will be cleaned up. Be sure to detach() it, and then attach() it later. Only use remove() when you're permanently popping a Fragment, and only use add() the first time you want to show it.
Then, you'll have to add some relatively simple logic to your TabListener. When a tab is unselected, simply peek() at its stack and detatch() the associated Fragment. When a tab is selected, peek() at the top of that stack and attach() that fragment.
Lastly, you'll have to deal with Activity lifecycle quirks (like orientation changes). Persist your Map of Stacks as well as the currently selected tab, and unpack it again in your onCreate(). (You don't get this packing and unpacking for free, but it's pretty easy to do.) Luckily your TabType enum is Serializable so it should be trivial to put into a Bundle.