Android Webview Tutorial with Example in android studio
how to make web browser in android studio using webview
Description:
Android webview- in this article, we will learn how to create an application for any website using webview.
Programming a simple android webview:
The following layout is part of the sample application WebView. It contains an object as the only visible component at runtime of type android.webkit.WebView. It completely occupies the width and height that are available for the activity.
1 2 3 4 5 6 7 8 |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> |
The interface is loaded and displayed on the one you are familiar with Way. The web address to be displayed is then given to the component passed by calling the loadUrl() method. the code is given below. By the way, if the page load fails, no exception is thrown.
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 |
package com.example.webview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView webview = (WebView) findViewById(R.id.webview); webview.loadUrl("https://www.google.com/"); } } |
Android webview Application for a website:
In this example, I’ll show you how to create simple Programming browsers with page history using the android webview.
Let’s first create a new project, for that simply click on the new project button
Then select the empty activity, and click the next button.
Then choose the application as per your requirement and click the finish button in my case I choose the application webView as you can see in the below image.
So our application is created successfully.
Let’s first take a look at the project’s layout file. I define a navigation bar with next and previous buttons as well as an input field for the website address. Below that is the android WebView component.
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 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/prev" android:text="prev" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/edittext" android:inputType="textUri" android:imeOptions="actionGo" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1.0" /> <Button android:id="@+id/next" android:text="next" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1.0" /> </LinearLayout> |
The android:inputType attribute configures text input behavior. The textUri value tells the system that the user sent a Uniform Resource Identifier to be entered. For example, pressing the (enter) key does not supply a line break. android:imeOptions affect the “Action” button of the virtual keyboard. actionGo states that the user entered the target as the text wants to head for. The MainActiviy class first loads the activity_main.xml layout file and displays her at. Then for the two buttons, prev and next OnClickListener registered. You guide the respective action to the WebView. This provides the goBack() and goForward() methods for this disposal. With canGoBack() and canGoForward() you can check whether this is currently possible. I use this in the updateNavBar() method to update the buttons to activate or deactivate. Incidentally, this method is used in only two places called. I’ll come back to that a little later.
In order to be able to react to the action command of the (virtual) keyboard, set an OnEditorActionListener for the text field. The only one to implement onEditorAction() method returns true if it has consumed the action. There I only use the code for the input line, I have to pass the method parameters do not check. Basically, given the values ​​of actionId and event recognize who triggered the action. My implementation reads the entered Text and passes it to loadUrl().
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 |
package com.example.webview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private Button prev, next; private EditText edittext; private WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); prev = (Button) findViewById(R.id.prev); next = (Button) findViewById(R.id.next); edittext = (EditText) findViewById(R.id.edittext); webview = (WebView) findViewById(R.id.webview); prev.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { webview.goBack(); } }); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = edittext.getText().toString(); webview.getSettings().setLoadsImagesAutomatically(true); webview.getSettings().setJavaScriptEnabled(true); webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webview.loadUrl(url); } }); edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { webview.loadUrl(v.getText().toString()); return true; } }); webview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { updateNavBar(); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { updateNavBar(); } }); webview.getSettings().setBuiltInZoomControls(true); webview.getSettings().setLoadWithOverviewMode(true); webview.getSettings().setUseWideViewPort(true); webview.getSettings().setLoadsImagesAutomatically(true); webview.getSettings().setJavaScriptEnabled(true); webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); if (savedInstanceState != null) { webview.restoreState(savedInstanceState); } else { webview.loadUrl("https://programmingdigest.com/"); } } private void updateNavBar() { prev.setEnabled(webview.canGoBack()); next.setEnabled(webview.canGoForward()); edittext.setText(webview.getUrl()); } } |
To react to events in the lifecycle of a WebView, use set- WebViewClient() an object that derives from the android.webkit.WebViewClient class. Its shouldOverrideUrlLoading() method is called when a URL should be loaded (e.g. because a link was clicked). The return value true indicates that the implementation wants to take care of the URL itself. If false, the WebView does this. If you only want to log page views, you could override the method but return false. Strictly speaking, my implementation is, therefore, unnecessary because it reflects the behavior that applies in this case recreates.
The onPageFinished() method is called when a page load is successful was completed. onReceivedError() indicates an error. In both cases, I update the navigation bar including the input field. For this reason,
my method updateNavBar() does not have to be called explicitly with loadUrl(). You’re almost there. getSettings() returns an object that you can use to get your android WebView can configure. For example, setBuiltInZoomControls() controls the Zoom controls. And with setJavaScriptEnabled() you can enable JavaScript turned off. We will address this topic in the next section. But before that, a tip: In order not to change the orientation of the device Losing page history and the currently viewed URL should be in your Override Activity onSaveInstanceState() and WebView method saveState() call. Restoring in onCreate() then looks like this:
1 2 3 4 5 6 7 |
if (savedInstanceState != null) { webview.restoreState(savedInstanceState); } else { webview.loadUrl("https://programmingdigest.com/"); } |
Unless the bundle passed to your activity is not null, call the WebView method restoreState() and pass it as the only parameter.
Load JavaScript in Android webview:
Here I will show you using the same example project WebView, How to use JavaScript code in your Android app. The Android WebView component offers a range of integration options. To use them, you must first use getSettings().setJavaScriptEnabled(true) Enable JavaScript capability. Now please see the following .html file. It defines a simple page consisting of a label, an input field, and a button. If you click on this, the function hello() is called. She clears the page content and greets the user. hello() becomes in defined in a <script /> tag. The value of its attribute type follows the “Scripting Media Types”. There is what is still frequently encountered on the net text/javascript marked as obsolete.
Paste the below code into index.html file and place the file into the assets folder
Now you might be wondering where index.html file is stored. You can use your apps “Include” files by copying them to the assets directory. This folder does not exist automatically. You may have to add it manually if necessary. To do this, right-click on the app, then click on new in the new menu click on the folder in folder menu click on assets folder
Now let’s take a look at the Activity that loads the .html file and indicates. the code is very short. the invocations of the methods You already know setContentView(), getSettings() and setJavaScriptEnabled().
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 |
package com.example.webview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webview = (WebView) findViewById(R.id.webview); webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setBuiltInZoomControls(true); webview.getSettings().setLoadWithOverviewMode(true); webview.getSettings().setUseWideViewPort(true); webview.getSettings().setLoadsImagesAutomatically(true); webview.getSettings().setJavaScriptEnabled(true); webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webview.setWebViewClient(new WebViewClient()); webview.loadUrl("file:///android_asset/index.html"); } private class WebViewClient extends android.webkit.WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } } } |
But the URL that we send to loadUrl() is interesting. The log file:// is followed by the absolute path /android_asset/index.html. This will make the file references index.html, which we copied into the assets directory. Even if the absolute path suggests this, the folder is not globally visible, by the way.
The final output of app:
Android webview Communicate with JavaScript:
The .html page appears in an activity, but otherwise has a life of its own. the code does not communicate with the rest of the app. It would be useful to look at the functions of the host system. Think of texts in different languages or to access contacts and calendars. JavaScript lets over Easily connect interfaces to native code. I’ll show you how to do that following. Please take a look at the communication class first. In this class, IÂ defined the two methods getHeadline() and message(). Both methods are annotated with @JavascriptInterface. In this way, you mark methods, which should be available in JavaScript.
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 |
package com.example.webview; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.os.Bundle; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webview = (WebView) findViewById(R.id.webview); webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setBuiltInZoomControls(true); webview.getSettings().setLoadWithOverviewMode(true); webview.getSettings().setUseWideViewPort(true); webview.getSettings().setLoadsImagesAutomatically(true); webview.getSettings().setJavaScriptEnabled(true); webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webview.setWebViewClient(new WebViewClient()); webview.addJavascriptInterface(new Communication(this), "Android"); webview.loadUrl("file:///android_asset/index.html"); } private class WebViewClient extends android.webkit.WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } } public class Communication{ private Context mContext; public Communication(Context c) { mContext = c; } @JavascriptInterface public String getHeadline() { return mContext.getString(R.string.headline); } @JavascriptInterface public void message(String m) { Toast toast = Toast.makeText(mContext, m, Toast.LENGTH_LONG); toast.show(); } } } |
getHeadline() returns a string that is stored in the strings.xml file with the ID headline defined. The string can be in different languages. The method message() displays a message in the form of a so-called toast. Toasts are useful when presenting short messages that are interesting for the user but not too important. An example is the successful saving of a record. Error messages, however, should Do not display on such information boards. To connect an interface to JavaScript, simply call the WebView method addJavascriptInterface() and pass it the object and an (any) Name by which the interface is referenced in the JavaScript code:
1 |
webview.addJavascriptInterface(new Communication(this), "Android"); |
this refers to the Activity containing the WebView. The file printed in the following listing index.html uses the Android interface. To try this out, all you have to do is Adjust the URL accordingly when calling the loadUrl() method.
Now copy the below code and paste it into the index.html file
Did you notice that the heading (in the h1 tag) is empty? She will through the Assignment headline.innerText = Android.getHeadline(); set. getHeadline() is here one of the methods of communication. Calling the second method, message(), takes place in the hello() function. By the way, you have to define your own Do not initialize interfaces on the JavaScript side. You stand without further action automatically available. Note, however, that the JavaScript-bound object is executed on a different thread than the one on which it is created became.
With the android WebView component, you have become acquainted with a powerful tool for Integrate websites into your app.