One of the very useful components in Android application development is the WebView component, powered by chrome. WebView allows Android apps to display web contents. In other words, one can easily show contents that pulls from the web in the Android app screen.
Our tutorial today will be about how to implement this feature in an Android application. This is an important feature to have in an Android app, in cases where you want users to load web pages without leaving your Android application. For example, loading your social media pages (Facebook, Twitter etc), privacy information on your website etc.
Below is a screen shot of what we will achieve in this tutorial. For this tutorial, we will be loading a web page, in this case (https://www.appdevchannel.com) from within our Android app.
Firstly, launch the Android Studio IDE and create a new project by selecting the Empty Activity from the list of available template.
(a) Open up the colors.xml file, which can be found under app/src/main/res/values, and add the below code snippet.
(b) Open the strings.xml file and paste the below code snippet into it. You will also find it at app/src/main/res/value
It’s time to design the WebView layout for our application.
Open up the layout folder at app/src/main/res and create a new Layout XML file. Name it activity_web_view.xml. Copy and paste the below code snippet.
The next step for us is to add two permissions in the AndroidManifest.xml.
(a) android.permission.INTERNET, which allows us to access the internet in order to load our data. In this case, our web content.
(b) android.permission.ACCESS_NETWORK_STATE, which allows us to check if user device has a working internet before making efforts to load data from the internet.
Copy and paste the code snippet below to update your AndroidManifest.xml file.
Finally, we need to create the WebViewActivity class. Create a new android activity named WebViewActivity and register it in the AndroidManifest.xml file. Copy and paste the below code snippet.
At this point, we are done with all the necessary codes required. Build the project and connect your Android device, click the run button and select your device as the target for deployment.