Tuesday, July 6, 2021

How to create a WebView in an Android App using Kotlin

Another scenario in which WebView can help is if your app provides data to the user that always requires an Internet connection to retrieve data, such as email. In this case, you might find that it's easier to build a WebView in your Android app that shows a web page with all the user data, rather than performing a network request, then parsing the data and rendering it in an Android layout. Instead, you can design a web page that's tailored for Android devices and then implement a WebView in your Android app that loads the web page.

This document shows you how to get started with How to create a WebView in an Android App using Kotlin do some additional things, such as handle page navigation and bind JavaScript from your web page to client-side code in your Android app

Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.

Step 2: Create layout

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"

   android:id = "@+id/parent"

   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">

   </WebView>

</RlativeLayout>

Step 3: Add the following code to src/MainActivity.kt

class MainActivity : AppCompatActivity() {

   private val webView: WebView? = null

   override fun onCreate(savedInstanceState: Bundle?) {

      super.onCreate(savedInstanceState)

      setContentView(R.layout.activity_main)

      title = "KotlinApp"

      val webView = findViewById<WebView>(R.id.webView)

      webView.webViewClient = WebViewClient()

      webView.loadUrl("https://www.google.com")

      val webSettings = webView.settings

      webSettings.javaScriptEnabled = true

   }

   override fun onBackPressed() {

      if (webView!!.canGoBack()) {

         webView.goBack()

      } else {

         super.onBackPressed()

      }

   }

}

Step 4: Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">

   <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/AppTheme">

      <activity android:name=".MainActivity">

         <intent-filter>

            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

         </intent-filter>

      </activity>

   </application>

</manifest>

No comments:

Post a Comment