dulan
dulan

Reputation: 1604

Android prevent webview reload in fragment

I have a main activity that contains a frame layout and 4 tab buttons, and there are in total 4 fragments, each fragment relates to a tab button, depending on which tab button is clicked, the corresponding fragment will be swapped into the frame layout to replace the old one. Now in each of the fragment there's a webview that loads different URL when the fragment is created. My question is how to prevent from the webview to reload every time when fragments swap? Below are the code how I swap my fragment:

FragmentMainPage fragment = new FragmentMainPage();
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.frameLayout, fragment);
transaction.commit();
currentPage = VT_Constants.HOME_PAGE;

Upvotes: 4

Views: 1645

Answers (3)

Siva
Siva

Reputation: 1198

I was also facing the same problem. Tried changing the webView Settings and none worked for me. This is not the problem with the webview.

The actual problem here is your fragment is a part of ViewPager. By default viewPager will have setOffscreenPageLimit as 1.

For one immediate tab switch, you will not see any refresh of the fragment. Post that you will face this issue.

You have to simply add this one line to your view pager if you don't want to refresh fragments

mViewPager.setOffscreenPageLimit(numOfTabs);

for ex:

mViewPager.setOffscreenPageLimit(10); //if you have 10 tabs

Hope this helps.

Upvotes: 1

HKB
HKB

Reputation: 41

You can set page limit.

viewPager.setOffscreenPageLimit(4);

Webviews won't reload anymore.

Upvotes: 0

Bruce
Bruce

Reputation: 2377

Calling replace is destructive: it tears down the fragment's view hierarchy, so when you add it back later, the views have to be rebuilt, which explains the behavior you are seeing.

Try show and hide instead. These maintain the fragment's views, so they can be re-attached to your activity when the user clicks on that fragment's tab. Something like this (although I'm not sure how you want to get the reference to the current fragment):

FragmentMainPage fragment = new FragmentMainPage();
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
Fragment oldFragment = fm.findFragmentByTag(...); // somehow get the current fragment showing
FragmentTransaction transaction = fm.beginTransaction();
transaction.hide(oldFragment);
transaction.show(fragment);
transaction.commit();

Upvotes: 3

Related Questions