In previous article, we have learnt basic concepts about android WebView. This article will give you a WebView example. Please note, it is better to run this example in a real android device, run it in android emulator may have errors.
1. Example Introduce.
There are five buttons in this example, when the url input text box is empty, click the load button will display a snippet of html code in WebView.
If you input a url start with http or https and click load button, WebView will display the web page. Click the links in the web page, it will display another web page in same webview object.
While web page is loading, it will display the load page process in the activity window title. When page load complete, it will display web page title in it.
Now click Prev button to go to previous page, and then click Next button to go to next page.
When click Clear button, all cached html file, webview history and html form data will be removed. Now Prev an Next button will not take effect.
Click Hello button will display a snippet of html code in webview also.
2. Project File Structure And Source Code.
2.1 Main activity.
WebviewActivity.java
Please note, below method must be placed at the beginning of onCreate method, otherwise an AndroidRuntimeException requestFeature() must be called before adding content will be thrown.
Window activityWindow = this.getWindow(); activityWindow.requestFeature(Window.FEATURE_PROGRESS);
package com.dev2qa.example.view.webview; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Button; import android.widget.EditText; import com.dev2qa.example.R; public class WebviewActivity extends AppCompatActivity { public static final String TAG_WEB_VIEW_EXAMPLE = "WEB_VIEW_EXAMPLE"; private EditText urlEditor; private Button loadUrlButton; private Button backButton; private Button forwardButton; private Button clearCacheButton; private Button showSnippetButton; private WebView webView; private CustomWebviewClient customWebviewClient; private CustomWebChromeClient customWebChromeClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Request show progress bar in the activity window title. Window activityWindow = this.getWindow(); activityWindow.requestFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.activity_webview); setTitle("dev2qa.com - Android WebView Example."); // Initialize this activity used controls. initControl(); // Click this button to load user specified web url page. loadUrlButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = urlEditor.getText().toString(); if(!TextUtils.isEmpty(url)) { webView.loadUrl(url); }else { webView.loadData("<font color=red><b>Please input web page url start with http or https, then click load button.</b></font>", "text/html", "utf-8"); } } }); // Click this button to go to previous page. backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(webView.canGoBack()) { webView.goBack(); } } }); // Click this button to go to next page. forwardButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(webView.canGoForward()) { webView.goForward(); } } }); // Click this button to clear webview cache, history and html form data. clearCacheButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Clear cache page. webView.clearCache(true); // Clear webview history. webView.clearHistory(); // Clear html form data. webView.clearFormData(); } }); showSnippetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { webView.loadData("<strong><font color=red>Hello WebView</font></strong>", "text/html", "utf-8"); } }); } // Initialize the edit text, buttons and WebView component. private void initControl() { urlEditor = (EditText)findViewById(R.id.web_view_url_editor); loadUrlButton = (Button)findViewById(R.id.web_view_load_button); backButton = (Button)findViewById(R.id.web_view_back_button); forwardButton = (Button)findViewById(R.id.web_view_forward_button); clearCacheButton = (Button)findViewById(R.id.web_view_clear_cache_button); showSnippetButton = (Button)findViewById(R.id.web_view_show_snippet_html); webView = (WebView)findViewById(R.id.web_view_component); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); // Set custom webview client. customWebviewClient = new CustomWebviewClient(); webView.setWebViewClient(customWebviewClient); // Set custom web chrome client. customWebChromeClient = new CustomWebChromeClient(); customWebChromeClient.setSourceActivity(this); webView.setWebChromeClient(customWebChromeClient); webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); } @Override protected void onDestroy() { // Destroy WebView object when activity is destroyed. if(webView!=null) { ViewGroup viewGroup = (ViewGroup) webView.getParent(); viewGroup.removeView(webView); webView.destroy(); webView = null; } super.onDestroy(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { // Process android device back menu if(webView!=null && webView.canGoBack()) { webView.goBack(); return true; } } return super.onKeyDown(keyCode, event); } }
2.2 Custom WebViewClient class.
CustomWebviewClient.java
package com.dev2qa.example.view.webview; import android.graphics.Bitmap; import android.util.Log; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Created by Jerry on 2/26/2018. */ public class CustomWebviewClient extends WebViewClient { @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "onPageStarted url : " + url); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "onPageFinished url : " + url); super.onPageFinished(view, url); } @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if(request!=null) { Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "shouldOverrideUrlLoading request.toString() : " + request.toString()); Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "shouldOverrideUrlLoading request.getUrl().toString() : " + request.getUrl().toString()); view.loadUrl(request.getUrl().toString()); }else { Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "shouldOverrideUrlLoading request is null."); } return false; } }
2.3 Custom WebChromeClient class.
CustomWebChromeClient.java
package com.dev2qa.example.view.webview; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebView; /** * Created by Jerry on 2/26/2018. */ public class CustomWebChromeClient extends WebChromeClient { private AppCompatActivity sourceActivity; private String webPageTitle = ""; public AppCompatActivity getSourceActivity() { return sourceActivity; } public void setSourceActivity(AppCompatActivity sourceActivity) { this.sourceActivity = sourceActivity; } // This method is invoked when webview load page. @Override public void onProgressChanged(WebView view, int newProgress) { // set title and sourceActivity.setTitle("Page Loading...... - dev2qa.com"); int showProgress = newProgress * 100; sourceActivity.setProgress(showProgress); if(newProgress == 100) { sourceActivity.setTitle(webPageTitle); } super.onProgressChanged(view, newProgress); Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "onProgressChanged newProgress : " + newProgress); } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); webPageTitle = title; Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "onReceivedTitle title : " + title); } @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "onJsAlert url : " + url + " , message : " + message); return super.onJsAlert(view, url, message, result); } @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "onJsConfirm url : " + url + " , message : " + message); return super.onJsConfirm(view, url, message, result); } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { Log.d(WebviewActivity.TAG_WEB_VIEW_EXAMPLE, "onJsPrompt url : " + url + " , message : " + message); return super.onJsPrompt(view, url, message, defaultValue, result); } }
2.4 Main Layout Xml File.
activity_webview.xml.java
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/web_view_url_editor" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Input a url to browse."/> <LinearLayout android:id="@+id/web_view_button_layout" android:layout_below="@id/web_view_url_editor" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/web_view_load_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Load"/> <Button android:id="@+id/web_view_back_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Prev"/> <Button android:id="@+id/web_view_forward_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Next"/> <Button android:id="@+id/web_view_clear_cache_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Clear"/> <Button android:id="@+id/web_view_show_snippet_html" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Hello" /> </LinearLayout> <WebView android:id="@+id/web_view_component" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/web_view_button_layout" android:background="@color/colorBlue"></WebView> </RelativeLayout>
2.5 Android Manifest Xml File.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.dev2qa.example"> <!-- Play web url audio file required permission. --> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".view.webview.WebviewActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Reference
There is no a Custom WebChromeClient class, post it here… You double paste the WebViewClient class twice….
Thanks, i have just updated the CustomWebChromeClient.java code.