Here is a code for a basic Fragment
which contains a WebView
.
WebFragment.java
public class WebFragment extends Fragment {
String TAG = "WebFragment";
private WebView webView;
private String currentUrl = "http://www.google.com";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.webview_layout, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
webView = (WebView) getView().findViewById(R.id.helloWebview);
initWebView();
webView.loadUrl(currentUrl);
}
@SuppressLint("SetJavaScriptEnabled")
private void initWebView() {
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.e(TAG, "Loding...");
super.onPageStarted(view, url, favicon);
}
});
}
class JavaScriptInterface {
public void showHTML(String html) {
}
}
}
I have 2 more basic fragments also(which doesn't have WebView
). Then I put all these 3 Fragments
in ViewPager
(WebFragment
, Fragment1
and Fragment2
respectively) using FragmentAdapter
. And I added android:configChanges="orientation|screenSize"
in AndroidManifest.xml
(So WebView
will not realod on configration change).
Now my problem is, While running app I changed the 1st page (WebFragmet) of ViewPager
to 2nd page(Fragment1
) and again I came back to 1st page. So no problem WebFragment
is as it is.
Now again I changed the ViewPager
like this WebFragment
-->Fragment1
-->Fragment2
and came back to 1st page by reversing the direction of above action. But at that time I saw the WebView
in WebFragment
is reloading.
And one more problem, whenever the WebView
started loading I can see 2 log entry like.
WebFragment Loading...
WebFragment Loading...
So my question is :
1) How can I prevent WebView
reloading when the WebFragment
is retained from BackStack
?
2) Why here WebView
loading twice?
Just see this question and help me(Prevent WebView reloads in FragmentPagerAdapter?).
In your main activity where you have defined viewpager
after the declaration of viewpager like this line :
ViewPager viewpager = (ViewPager) findViewById(R.id.pager);
add this line :
viewpager.setOffscreenPageLimit(2);
This will prevent your fragment from recreated upto swipe of two screens,so when you will return from 3rd page to 1st page in viewpager,your webview will not reload.