We had learn basic things about WebView in my earlier tutorial. In that tutorial i am showing how to load url in WebView. But in today’s tutorial we are going to learn some more things about WebView. The things that we are going to learn today are given below:
1 . Go Back – We can go back to previous page in WebView if present.
1 2 |
if (webView.canGoBack()) webView.goBack(); |
2 . Go Forward – We can go forward to next page in WebView if present.
1 2 |
if (webView.canGoForward()) webView.goForward(); |
3. Refresh WebView – We can fetch currentWebView url and reload the WebView.
1 |
String url = webView.getUrl();//Get webview url |
1 |
webView.loadUrl(url);//Load fetched Url |
4. Error Catching – We can catch errors thrown by WebView occurred by HTTP error,etc. inside WebViewClient class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); Toast.makeText(MainActivity.this, "Unexpected error occurred.Reload page again.", Toast.LENGTH_SHORT).show(); } @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); Toast.makeText(MainActivity.this, "Unexpected error occurred.Reload page again.", Toast.LENGTH_SHORT).show(); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); Toast.makeText(MainActivity.this, "Unexpected SSL error occurred.Reload page again.", Toast.LENGTH_SHORT).show(); } |
There are two other things apart from above four steps that we are going to learn are:
1. UserFriendly UI design – I am going to create a Custom Toolbar with some ImageViews as shown in video below.
2. No ActionBar Activity – Since I am creating custom toolbar so we don’t need ActionBar so for that we need our activity withoutActionBar.
1. Create a new project in Android Studio by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Create a layout naming activity_main.xml and add the following xml code into it. In this code i had created a custom toolbar at top and added some ImageView and title to it and placed WebView below it.
You can download icons from here. This is a best site to download icons for all sizes, colours and of all app platforms.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#FFFDFE" android:minHeight="?attr/actionBarSize"> <ImageView android:id="@+id/webviewBack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_margin="5dp" android:background="@drawable/imageview_selector" android:padding="5dp" android:src="@drawable/ic_back" /> <ImageView android:id="@+id/webviewForward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_margin="5dp" android:layout_toRightOf="@+id/webviewBack" android:background="@drawable/imageview_selector" android:padding="5dp" android:src="@drawable/ic_forward" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:padding="5dp" android:text="ANDROHUB" android:textColor="#2196F3" android:textSize="16sp" /> <ImageView android:id="@+id/webviewReload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_margin="5dp" android:layout_toLeftOf="@+id/webviewClose" android:background="@drawable/imageview_selector" android:padding="5dp" android:src="@drawable/ic_refresh" android:visibility="gone" /> <ProgressBar android:id="@+id/webViewProgressBar" android:layout_width="23dp" android:layout_height="23dp" android:layout_centerVertical="true" android:layout_gravity="end" android:layout_margin="10dp" android:layout_toLeftOf="@+id/webviewClose" android:visibility="gone" /> <ImageView android:id="@+id/webviewClose" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_margin="5dp" android:background="@drawable/imageview_selector" android:padding="5dp" android:src="@drawable/ic_close" /> </RelativeLayout> <View android:layout_width="fill_parent" android:layout_height="1px" android:background="#7e7e7e" /> <WebView android:id="@+id/sitesWebView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> |
3. Now create a xml drawable file under drawable folder naming imageview_selector.xml for background selector for ImageViews.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <shape android:shape="rectangle"> <solid android:color="#cccacb" /> </shape> </item> <item> <shape android:shape="rectangle"> <solid android:color="@android:color/transparent" /> </shape> </item> </selector> |
4. Now create a MainActivity.java and add the following code. In this code all above discussed steps are included.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
package com.advancewebview; import android.content.Context; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.http.SslError; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.View; import android.webkit.SslErrorHandler; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static WebView webView; private static ProgressBar webViewProgressBar; private static ImageView back, forward, refresh, close; private static final String webViewUrl = "https://androhub.com"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); setUpWebView(); setListeners(); } private void initViews() { back = (ImageView) findViewById(R.id.webviewBack); forward = (ImageView) findViewById(R.id.webviewForward); refresh = (ImageView) findViewById(R.id.webviewReload); close = (ImageView) findViewById(R.id.webviewClose); webViewProgressBar = (ProgressBar) findViewById(R.id.webViewProgressBar); } private void setUpWebView() { webView = (WebView) findViewById(R.id.sitesWebView); webView.setWebViewClient(new MyWebViewClient()); webView.getSettings().setJavaScriptEnabled(true); LoadWebViewUrl(webViewUrl); } private void setListeners() { back.setOnClickListener(this); forward.setOnClickListener(this); refresh.setOnClickListener(this); close.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.webviewBack: isWebViewCanGoBack(); break; case R.id.webviewForward: if (webView.canGoForward()) webView.goForward(); break; case R.id.webviewReload: String url = webView.getUrl(); LoadWebViewUrl(url); break; case R.id.webviewClose: finish(); break; } } private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); refresh.setVisibility(View.GONE); if (!webViewProgressBar.isShown()) webViewProgressBar.setVisibility(View.VISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); refresh.setVisibility(View.VISIBLE); if (webViewProgressBar.isShown()) webViewProgressBar.setVisibility(View.GONE); } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); refresh.setVisibility(View.VISIBLE); if (webViewProgressBar.isShown()) webViewProgressBar.setVisibility(View.GONE); Toast.makeText(MainActivity.this, "Unexpected error occurred.Reload page again.", Toast.LENGTH_SHORT).show(); } @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); refresh.setVisibility(View.VISIBLE); if (webViewProgressBar.isShown()) webViewProgressBar.setVisibility(View.GONE); Toast.makeText(MainActivity.this, "Unexpected error occurred.Reload page again.", Toast.LENGTH_SHORT).show(); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); refresh.setVisibility(View.VISIBLE); if (webViewProgressBar.isShown()) webViewProgressBar.setVisibility(View.GONE); Toast.makeText(MainActivity.this, "Unexpected SSL error occurred.Reload page again.", Toast.LENGTH_SHORT).show(); } } // To handle "Back" key press event for WebView to go back to previous screen. @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { isWebViewCanGoBack(); return true; } return super.onKeyDown(keyCode, event); } private void isWebViewCanGoBack() { if (webView.canGoBack()) webView.goBack(); else finish(); } private void LoadWebViewUrl(String url) { if (isInternetConnected()) webView.loadUrl(url); else { refresh.setVisibility(View.VISIBLE); Toast.makeText(MainActivity.this, "Oops!! There is no internet connection. Please enable your internet connection.", Toast.LENGTH_LONG).show(); } } public boolean isInternetConnected() { // At activity startup we manually check the internet status and change // the text status ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; } } |
5. To open url in WebView we need Internet Connection so for that we have to give “INTERNET” permission in Manifest file also we are checking internet connection before loading any url so for that we need “ACCESS_NETWORK_STATE” permission in Manifest file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.advancewebview" > <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:theme="@style/FullScreen" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
6. Finally add below FullScreen style code inside styles.xml file. This style is used for making our activity fullscreen as i mentioned above.
1 2 3 4 5 6 |
<style name="FullScreen" parent="@style/Theme.AppCompat.Light"> <item name="windowNoTitle">true</item> <item name="windowActionBar">false</item> <item name="android:windowFullscreen">true</item> <item name="android:windowContentOverlay">@null</item> </style> |
7. Now, you are all done, run your app and you will get the output as shown in video.
Make sure to put http:// or https:// before loading url and change your url instead of androhub.com or you can refer to my earlier tutorial to load url by taking user input.
Thanks.
Subscribe to us and get the latest news.
3 Comments
Kapil
Thursday, January 26th, 2017I want to create a listview with image and text in each element of list.
Also the elements must be like hidden checklist when user clicks color of the elements clicked changes and when submits
all selections must pass to another class or activity.
Ram
Friday, June 1st, 2018Great Tutorial!! Youtube Videos are not playing in full screen mode.
Raj singh
Wednesday, February 13th, 2019I have the same issue as ram and I want a horizontal progress bar which increases with time but mine show max at the start. please help me to understand this.