In the previous article, we have learned basic concepts about android WebView. This article will give you a WebView example. Please note, it is better to run this example on a real android device, run it in an android emulator may have errors.
If you can not watch the above video, you can see it on the youtube URL https://youtu.be/NdurJlwHfCY
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 the LOAD button, WebView will display the web page. Click the links on the web page, it will display another web page in the same WebView object.
- While the web page is loading, it will display the load page process in the activity window title.
- When the page load is complete, it will display the web page title in it.
- Now click the PREV button to go to the previous page, and then click the NEXT button to go to the next page.
- When clicking the CLEAR button, all cached Html files, WebView history, and Html form data will be removed, then the PREV and NEXT buttons will not take effect.
- Click the HELLO button will display a snippet of Html code in WebView also.
2. Project File Structure And Source Code.
- Below is the example project source files list.
C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\EXAMPLE\APP\SRC\MAIN\JAVA\COM\DEV2QA\EXAMPLE\VIEW\WEBVIEW CustomWebChromeClient.java CustomWebviewClient.java WebviewActivity.java
2.1 Main Activity.
- Please note, the below method must be placed at the beginning of the onCreate method.
Window activityWindow = this.getWindow(); activityWindow.requestFeature(Window.FEATURE_PROGRESS);
- Otherwise, an AndroidRuntimeException requestFeature() must be called before adding content will be thrown.
- WebviewActivity.java
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; 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; 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
<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.