WebView in an Android App using Kotlin language
WebView is used to display web pages. if you want to display web content inside your app then this view will help you.in this article, you will learn how to WebView in an Android App using Kotlin. webView allows user to integrate a webpage as a part of the android app. from this post we will we build a basic Android Web View using Kotlin language. you can use it to create web-based using this process.
You may know also:
Android Calculator in Kotlin Using Android Studio
Expandable List View code snippet for Android Studio
Android Studio TextSwitcher using kotlin Language
Create a WebView using Kotlin language
Follow the below step to create new webview android studio project using kotlin language. if you already create new android studio project then ignore the below steps.
- First Open Android Studio.
- Now click on file -> New -> New Project .
- Now write your project name and select kotlin language from dropdown menu and click next button.
- Then select empty activity and click finish button.
- that’s it.
Then open the AndroidMenifest.xml file and add uses permission for internet to get internet access.
1 |
<uses-permission android:name="android.permission.INTERNET"/> |
add this webview xml below code to your app in the activity_main.xml file.
activity_main.xml
1 2 3 4 5 6 7 8 |
<WebView 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" android:id="@+id/web"> </WebView> |
Now add the following below code in the MainActivity class. we are use loadUrl() method for load web url.
MainActivity.kt
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 |
import android.os.Bundle import android.view.View import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_webview.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var m: WebView? = null m = findViewById<View>(R.id.web) as WebView val webSettings: WebSettings = m.getSettings() webSettings.javaScriptEnabled = true m.setWebViewClient(WebViewClient()) m.loadUrl("https://www.google.com/") fun onPause() { super.onPause() m.onPause() } fun onResume() { super.onResume() m.onResume() } } } |
that’s it! Let’s try to run your application, and you will get a WebView embedded in the app. you will get output as shown below.
download source code from github