In this article, we will learn about android WebView using Kotlin. We will go through various example that demonstrates how to use different attributes of WebView. For example,
In this article, we will get answer to questions like –
- What is WebView?
- Why should we consider WebView while designing ui for any app?
- What are possibilities using WebView while designing ui? etc.
- How do we use webView to display webpage, local files etc.
We have covered only basic stuffs of webView in this post. For example,
– Display webpage of given url into WebView.
– Display Custom HTML into WebView.
– Display Local File Into WebView.
If you want to customise webView or do some settings in it, there is a separate post for it.
Output
Getting Started
We can define android WebView widget as below –
WebView is a widget that is used to display webpages in any android application. Using this class, you can also implement your own web browser or simply display online content within your activity in the application.
Webkit rendering engine is used in webView to provide features such as –
– 1. Display webpages
– 2. Includes methods to navigate forward and backward through history.
– 3. Zoom in zoom out
– 4. Text Searches and many more things
Now, how do we use WebView in android application ?
Creating New Project
At first, we will create an application.
So, follow steps below to create any android project in Kotlin –
Step | Description |
---|---|
1. | Open Android Studio (Ignore if already done). |
2. | Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next. |
3. | In next screen, select project name as WebView. Then, fill other required details. |
4. | Then, clicking on Finish button creates new project. |
Newbie in Android ?
Some very important concepts (Recommended to learn before you move ahead)
Before we move ahead, we need to setup for viewBinding to access Android WebView Using Kotlin file without using findViewById() method.
Setup ViewBinding
Add viewBinding true in app/build.gradle file.
android { // OTHER CODE... buildFeatures { viewBinding true } }
Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) } }
Now, we can access view in Kotlin file without using findViewById() method.
Using WebView in Kotlin
We can load many types of pages into WebView. For example,
- Showing custom HTML into WebView.
- Showing Webpage of given URL into WebView.
- Displaying data of given file path into WebView.
Now, we will go through each one by one –
1. Showing Custom HTML into WebView
Follow steps below to use WebView in newly created project –
- Open res/values/strings.xml file. Then, add below code into it.
<resources> <string name="app_name">WebView</string> </resources>
- Open res/layout/activity_main.xml file. Then, add below code in it –
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
-
We can also access it in Kotlin File, MainActivity.kt, as below –
package com.tutorialwing.webview import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.tutorialwing.webview.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) setupHTMLWebView() } private fun setupHTMLWebView() { val htmlText = "<html><body>" + "<p>Hello, Tutorialwing!</p> <p>How are you?</p>" + "</body></html>" binding.webView.loadData(htmlText, "text/html", "UTF-8") } }
Here, loadData(…) method has been used to load custom HTML data into webView.
Now, run the application. We will get output as below –
2. Showing Webpage of given URL into WebView
Follow steps below to use WebView in newly created project –
- Open res/values/strings.xml file. Then, add below code into it.
<resources> <string name="app_name">WebView</string> <string name="site_url">https://tutorialwing.com</string> </resources>
- Open res/layout/activity_main.xml file. Then, add below code in it –
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
- Since we are accessing webpage of given url, we need internet permission in app. So, add internet permission in AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tutorialwing.webview"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.WebView"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
-
We can also access WebView in Kotlin File, MainActivity.kt, as below –
package com.tutorialwing.webview import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.tutorialwing.webview.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) setupURLWebView() } private fun setupURLWebView() { val webView = binding.webView webView.loadUrl(getString(R.string.site_url)) } }
Here, loadUrl(…) method has been used to load webpage into webView. getString(R.string.site_url) returns the url of the webpage to be loaded.
Now, run the application. We will get output as below –
3. Displaying data of given File Path into WebView
Follow steps below to use WebView in newly created project –
- Add any image you wish to load into webView in res/drawable folder.
Here, we have added tutorialwing_logo.png. If you wish, you can download it from source-code. - Open res/layout/activity_main.xml file. Then, add below code in it –
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
-
We can also access it in Kotlin File, MainActivity.kt, as below –
package com.tutorialwing.webview import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.tutorialwing.webview.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) setupFilePathWebView() } private fun setupFilePathWebView() { var html = "<html><head><title>TITLE!!!</title></head>" html += "<body>" + "<h3>Tutorial by tutorialwing.com</h3>" + "<img src=\"tutorialwing_logo.png\" />" + "</body>" + "</html>" // Provide relative url to the base... val baseUrl = "file:///android_res/drawable/" val data = html val mimeType = "text/html" val encoding = "UTF-8" val historyUrl: String? = null binding.webView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl) } }
Here, we have used loadDataWithBaseURL(…) method to load data from local file into webView.
Now, run the application. We will get output as below –
Different Attributes of WebView in XML
Now, we will see how to use different attributes of Android WebView using Kotlin to customise it –
Set Id of WebView
Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of WebView using android:id attribute like below –
<WebView android:id="@+id/webView_ID" />
Here, we have set id of WebView as webView_ID using android:id=”” attribute. So, if we need to reference this WebView, we need to use this id – webView_ID.
Set Width of WebView
We use android:layout_width=”” attribute to set width of WebView.
We can do it as below –
<WebView android:id="@+id/webView_ID" android:layout_width="wrap_content" />
Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Set Height of WebView
We use android:layout_height=”” attribute to set height of WebView.
We can do it as below –
<WebView android:id="@+id/webView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" />
Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Set Padding of WebView
We use android:padding=”” attribute to set padding of WebView.
We can do it as below –
<WebView android:id="@+id/webView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" />
Here, we have set padding of 10dp in WebView using android:padding=”” attribute.
Set Margin of WebView
We use android:layout_margin=”” attribute to set margin of WebView.
We can do it as below –
<WebView android:id="@+id/webView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" />
Here, we have set margin of 10dp in WebView using android:layout_margin=”” attribute.
Set Background of WebView
We use android:background=”” attribute to set background of WebView.
We can do it as below –
<WebView android:id="@+id/webView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ff0000" />
Here, we have set background of color #ff0000 in WebView using android:background=”” attribute.
Set Visibility of WebView
We use android:visibility=”” attribute to set visibility of WebView.
We can do it as below –
<WebView android:id="@+id/webView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" />
Here, we have set visibility of WebView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Different Attributes of Android WebView Widget
Below are the various attributes that are used to customise android WebView Widget. However, you can check the complete list of attributes of WebView in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –
Some of the popular attributes of android webView widget inherited from ViewGroup are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:clipChildren | Specifies whether a child is limited to draw inside of its bounds or not |
2 | android:layoutAnimation | Specifies the layout animation to use when the viewGroup is laid out for the first time |
3 | android:persistentDrawingCache | Specifies the persistent of the drawing cache |
4 | android:layoutMode | Specifies layout mode this viewGroup |
Some of the popular attributes of android WebView inherited from View are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:alpha | Specifies alpha of the view |
2 | android:background | Specifies drawable to be used for the background |
3 | android:contextClickable | Specifies whether this view should react to context click event |
4 | android:elevation | Specifies base z depth of the view |
5 | android:fitsSystemWindows | It is used to adjust view layout based on system windows such as status bar etc. It accepts true or false value. |
6 | android:foreground | Specifies the drawable to draw over the content |
7 | android:foregroundGravity | Specifies the gravity of the foreground drawable |
We have seen different attributes of WebView and how to use it. If you wish to visit post to learn more about it
Thus, we have seen what is WebView, how can we use android WebView using Kotlin ? etc. We also went through different attributes of android WebView.
For some reason, after completing steps “Showing Webpage of given URL into WebView” the page is shown in my default Firefox browser, not inside my app. Can you, please, advise, what could I miss? Thanks