Android WebView is a system component that is powered by Google Chrome. It allows android apps to display web content. WebView is the part of the Android OS responsible for rendering web pages in most Android apps.
Basically, WebView is a view that display web pages inside your application. We can also specify HTML string and can show it inside our application using WebView.
In android mainly we can develop 2 types of applications:
A web-to-native abstraction layer enables access to device capabilities that are not accessible in Mobile Web applications, such as the accelerometer, camera and local storage.
I will cover this topic in detail in my next tutorial.
We can add webview in our main layout file as given below:
If we want to load data from a remote URL, our application needs permission to access the internet. This permission needs to be added in the application's manifest file.
To add Internet permission, add below given line just before application element:
The next step is to call the loadUrl method on the webview. Add the following line to the end of the onCreate method.
To handle navigation inside the WebView you need to override the WebView's WebViewClient, which handles various events generated by the WebView. You can use it to control how the WebView handles link clicks and page redirects.
Suppose we want to open internal urls in webview and external url in a browser, in that case we must override shouldOverrideUrlLoading method of WebViewClient class, thats the reason why I created a subclass of WebViewClient.
Write below given code to your main activity class:
To create an assets folder follow the steps:
To prevent WebView refresh on orientation change just add android:configChanges="orientation|screenSize" to the relevant Activity in your manifest. By setting this flag you are telling Android System to not destroy the Activity and that you're going to handle all orientation changes (if any) by yourself.
Now, lets combine all the discussion points to create a sample of webview.
Step 1: Create a new project in Android Studio and name it Android WebView.
Step 2:Open res -> drawable -> activity_main.xml and replace the code with code of activity_main.xml with the below given code.activity_main.xml
Step 3:Open manifests -> AndroidManifest.xml and replace the code with code of AndroidManifest.xml with the below given code.AndroidManifest.xml
Step 4: Create a new class MyWebViewClient and replace its code with below given code.MyWebViewClient.java
Step 5: Open MainActivity.java and replace its code with below given code.
Step 6:Clean and run your project to see the result.