The idea for this post came to me after reading the comment of Esthon Wood: “do you have any idea on how to save the state of the WebView? I mean, the webview refreshes everytime I tap on the tab.” in the post Tab Layout in Android with ActionBar and Fragment.
As a starting point I suppose that you have properly configured the example explained in Tab Layout in Android with ActionBar and Fragment.
In the following steps I configure a WebView in the second tab:
- replace the file res/layout/tab2.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tab2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <WebView android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
- replace the eu/lucazanini/Tab2Fragment.java
package eu.lucazanini; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout; public class Tab2Fragment extends Fragment { private WebView webView; private Bundle webViewBundle; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.tab2, container, false); webView = (WebView) ll.findViewById(R.id.webView1); webView.setWebViewClient(new WebViewClient()); if (webViewBundle == null) { webView.loadUrl("http://www.lucazanini.eu"); } else { webView.restoreState(webViewBundle); } return ll; } @Override public void onPause() { super.onPause(); webViewBundle = new Bundle(); webView.saveState(webViewBundle); } }
- row 24: I set the variable webView to the WebView in the layout res/layout/tab2.xml
- row 25: with this instruction the WebView is displayed under the second tab, and not in full screen hiding the Action Bar, and every link is opened reusing the same webView without opening the default browser; the issue is that I no longer have the address bar
- row 38: method onPause, here I save the state of the webView in the Bundle webViewBundle; the method onPause is called when the Fragment is going into the background (for example when I select the other tab), after the reselection of the second tab, in the onCreate method after verifying that there is a webViewBundle not null, I use it to restore the state of the WebView (row 30)
- add a permission to access to internet in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
- launch the app
For other configurations of the WebView, such as to enable JavaScript, you can refer to Building Web Apps in WebView.
Leave a Reply