Android’s WebView allows you to open an own windows for viewing URL or custom html markup page.
WebView is a view that display web pages inside your application. You can also specify HTML string and can show it inside your application using WebView. WebView makes turns your application to a web application.
In order to add WebView to your application, you have to add <WebView> element to your xml layout file. Its syntax is as follows −
1 2 3 4 |
<WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> |
In order to use it, you have to get a reference of this view in Java file. To get a reference, create an object of the class WebView. Its syntax is −
1 |
WebView web = (WebView) findViewById(R.id.webview); |
In order to load a web url into the WebView, you need to call a method loadUrl(String url)of the WebView class, specifying the required url. Its syntax is –
1 |
web.loadUrl("your url"); |
Apart from just loading url, you can have more control over your WebView by using the methods defined in WebView class. They are listed as follows −
Method | Description |
---|---|
canGoBack() | This method specifies the WebView has a back history item. |
canGoForward() | This method specifies the WebView has a forward history item. |
clearHistory() | This method will clear the WebView forward and backward history. |
destroy() | This method destroy the internal state of WebView. |
findAllAsync(String find) | This method find all instances of string and highlight them. |
getProgress() | This method gets the progress of the current page. |
getTitle() | This method return the title of the current page. |
getUrl() | This method return the url of the current page. |
If you click on any link inside the webpage of the WebView , that page will not be loaded inside your WebView. In order to do that you need to extend your class fromWebViewClient and override its method. Its syntax is −
1 2 3 4 5 6 7 |
private class MyBrowser extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } |
In this tutorial, we are going to learn how to use WebView in our app to open URLs inside our App.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. 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 26 27 28 29 30 31 32 33 34 35 36 37 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.web_view_demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <!-- Permission required for loading urls --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Permission required for checking internet connection --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".WebActivity" android:theme="@android:style/Theme.NoTitleBar" > </activity> <activity android:name="com.web_view_demo.MainActivity" 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> |
3. Create a xml layout naming activity_main.xml this layout contains edittext for input of url and button to load url in WebView below the button.
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 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:text="@string/text" android:textColor="#0587d9" android:textSize="18sp" android:textStyle="bold" /> <EditText android:id="@+id/url" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:gravity="center" android:hint="@string/enter_url" android:inputType="textUri" android:padding="10dp" android:singleLine="true" android:textColor="#000000" android:textSize="15sp" /> <Button android:id="@+id/open_url" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="5dp" android:text="@string/open_url" android:textSize="15sp" /> <!-- Web View to open URL --> <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> |
4. Finally come to your MainActivity.java and add the following code. In this code we validate the entered url on button click before loading over webview and also checking internet connection.
If you are unaware of how to check internet connection then you can read my tutorial here.
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 |
package com.web_view_demo; import android.app.ProgressDialog; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Patterns; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static WebView web; private static ProgressDialog dialog; private static EditText enter_url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); web = (WebView) findViewById(R.id.webview); enter_url = (EditText) findViewById(R.id.url); // Implement click listener over button findViewById(R.id.open_url).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { String url = enter_url.getText().toString();// Get editext text // into string // Check if string url is not null if (url.equals("") || url.length() == 0) // If null then display toast Toast.makeText(MainActivity.this, "Please enter a url.", Toast.LENGTH_SHORT).show(); else if // Check if entered url is valid or not and if it is not // valid then show toast (!Patterns.WEB_URL.matcher(url).matches()) Toast.makeText(MainActivity.this, "Entered URL is not Valid.", Toast.LENGTH_SHORT) .show(); else { // Check if interent is there or not if (isConnectingToInternet()) // if both above conditions falls then load url loadUrl(url); else Toast.makeText(MainActivity.this, "There is no Interent connection.", Toast.LENGTH_SHORT).show(); } } }); } // Load url method in webview private void loadUrl(String url) { // Progressdialog to show when url is loading dialog = new ProgressDialog(MainActivity.this); dialog.setMessage("Please wait..nWhile loading URL"); dialog.setCancelable(true);// Make it cancelable true so that user can // dismiss it anytime web.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { // On page finished loading dismiss dialog if (dialog.isShowing()) { dialog.dismiss(); } } }); dialog.show();// Show dialog web.loadUrl(url);// Load url into webview web.getSettings().setJavaScriptEnabled(true);// Enable javascript } // Return status of internet connection private boolean isConnectingToInternet() { ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } return false; } } |
5. 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).
Thanks.
Subscribe to us and get the latest news.