Webview kotlin android studio

Android WebView app Example in Kotlin code

With an Android WebView, you can show the website in an android application. Web-view is containers like scrollView, ListView, etc in Android app development. You can add it using Android studio drag-drop or in XML code directly. The purpose of WebView is if you want a web application or just a web page in your app

In Android WebView class is an extension of Android’s View class that allows you to display web pages as a part of your activity layout or other resources layout.

Android WebView app Example in Kotlin android studio

Let’s build an Android webView application

In this example, we are using Kotlin language with WebView and showing Responsive website in mobile. Also, we will add “If web view has back history, then go to the web view back history”.

Simply Adding a WebView to Your Application

To add a WebView to your Application, simply include the element in your resource layout file. For example, here’s a layout file in which the WebView match the screen, if you are suing LinearLayout or Relative Layout for ConstraintLayout you have to set with GUI builder (drag and drop).

To load a web page in the WebView , use loadUrl() . For example:

private val url = "https://tutorial.eyehunts.com/" webview.loadUrl(url)

Before this will work, however, your application must have access to the Internet. To get Internet access, request the INTERNET permission in your manifest file. For example:

Читайте также:  Troubleshooting guide for java

Enabling JavaScript

JavaScript is disabled in a WebView by default. If your website is using JavaScript (Nowadays every side using) then you must have to enable JavaScript.

// Get the web view settings instance

val setting = webview.settings;

// Enable javascript in web view

When you go inside webpage to webpage and then click Back button app will close. So you can override back button override fun onBackPressed() and Handle back press.

override fun onBackPressed() < if (webview.canGoBack()) < // If web view have back history, // then go to the web view back history webview.goBack() >>

More web view settings

You can handle more setting of web view like :

  • Enable javascript in web view
  • Enable and setup web view cache
  • Enable zooming in web view
  • Zoom web view text
  • Enable disable images in web view
  • safeBrowsingEnabled

Complete code

Create an android project in the android studio (Follow this tutorial: Android First Program in Android Studio)

Add WebView in main_activity.xml, used ConstraintLayout

Add fowling code in MainActiviyt.xml, the code in Kotlin, know more about basic fundamentals of kotlin

package `in`.eyehunt.webviewexample import android.graphics.Bitmap import android.os.Build import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < private val url = "https://tutorial.eyehunts.com/" override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Get the web view settings instance val settings = webview.settings; // Enable java script in web view settings.javaScriptEnabled = true // Enable and setup web view cache settings.setAppCacheEnabled(true) settings.cacheMode = WebSettings.LOAD_DEFAULT settings.setAppCachePath(cacheDir.path) // Enable zooming in web view settings.setSupportZoom(true) settings.builtInZoomControls = true settings.displayZoomControls = true // Zoom web view text //settings.textZoom = 125 // Enable disable images in web view settings.blockNetworkImage = false // Whether the WebView should load image resources settings.loadsImagesAutomatically = true // More web view settings if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) < settings.safeBrowsingEnabled = true // api 26 >//settings.pluginState = WebSettings.PluginState.ON settings.useWideViewPort = true settings.loadWithOverviewMode = true settings.javaScriptCanOpenWindowsAutomatically = true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) < settings.mediaPlaybackRequiresUserGesture = false >// More optional settings, you can enable it by yourself settings.domStorageEnabled = true settings.setSupportMultipleWindows(true) settings.loadWithOverviewMode = true settings.allowContentAccess = true settings.setGeolocationEnabled(true) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) < settings.allowUniversalAccessFromFileURLs = true >settings.allowFileAccess = true // WebView settings webview.fitsSystemWindows = true /* if SDK version is greater of 19 then activate hardware acceleration otherwise activate software acceleration */ webview.setLayerType(View.LAYER_TYPE_HARDWARE, null) webview.loadUrl(url) // Set web view client webview.webViewClient = object : WebViewClient() < override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) < // Page loading started // Do something >override fun onPageFinished(view: WebView, url: String) < // Page loading finished // Enable disable back forward button >> > override fun onBackPressed() < if (webview.canGoBack()) < // If web view have back history, then go to the web view back history webview.goBack() >> >

Note: Don’t forget to add internet permission in AndroidManifest.xml

It will throw an error or not upload webpage in the app.

Output screenshot android web view app :

android web view example

Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 7.1.1 ( Android Nougat), compile SDK version API 26: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”26″

Coding in JAVA

Источник

WebView Example in Android (Kotlin)

android webview example

Welcome Guys, In this WebView Example, we’ll learn how to build web apps using WebView in Android. Android WebView mostly used to display web pages as a part of your app. WebView is a subclass of View. It specially wrote for showing a webpage in your activity.

In this article, we’ll create a sample application, that contains WebView with ProgressBar. We’ll see how to handle back press event as well

Uses of WebView

WebView is very helpful if you want to show some HTML and javascript content in-app. Such as end-user agreement or a user guide.

WebView Sample App
1 Create a new project

Let’s open the AndroidStudio and create a new project with some default template. Now open the android manifest file and add uses permission for internet

2. Let’s create WebActivity

Navigate the file menu and create a new activity with a layout file named is WebActivity. Open the layout file and paste the below code. This layout file we are taking web view and progress bar

3. Let’s move to WebActivity

In source file initialized WebChromeClient using below code. webview settings you can changes as uses. One more thing that I do in this block of code is override onReceivedSslError.

@SuppressLint("SetJavaScriptEnabled") private fun initWebView() < webView.settings.javaScriptEnabled = true webView.settings.loadWithOverviewMode = true webView.settings.useWideViewPort = true webView.settings.domStorageEnabled = true webView.webViewClient = object : WebViewClient() < override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) < handler?.proceed() >> >
4. Set WebChromeClient to WebView

In this crome client, we override onProgressChanged() methods. Based on the progress we are showing and hiding progress bar

private fun setWebClient() < webView.webChromeClient = object : WebChromeClient() < override fun onProgressChanged( view: WebView, newProgress: Int ) < super.onProgressChanged(view, newProgress) progressBar.progress = newProgress if (newProgress < MAX_PROGRESS && progressBar.visibility == ProgressBar.GONE) < progressBar.visibility = ProgressBar.VISIBLE >if (newProgress == MAX_PROGRESS) < progressBar.visibility = ProgressBar.GONE >> > >
5. Manage web page history
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean < // Check if the key event was the Back button and if there's history if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) < webView.goBack() return true >// If it wasn't the Back key or there's no web page history, exit the activity) return super.onKeyDown(keyCode, event) >
6. Create loadUrl function

private fun loadUrl(pageUrl: String)

7. Finally, the full source of WebActivity looks like below

This is a full source of this activity, Still, you are missing some things I’ll add source code on below as well

package com.webviewexample import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.net.http.SslError import android.os.Bundle import android.view.KeyEvent import android.webkit.SslErrorHandler import android.webkit.WebChromeClient import android.webkit.WebView import android.webkit.WebViewClient import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_web.* class WebActivity : AppCompatActivity() < companion object < const val PAGE_URL = "pageUrl" const val MAX_PROGRESS = 100 fun newIntent(context: Context, pageUrl: String): Intent < val intent = Intent(context, WebActivity::class.java) intent.putExtra(PAGE_URL, pageUrl) return intent >> private lateinit var pageUrl: String override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_web) // get pageUrl from String pageUrl = intent.getStringExtra(PAGE_URL) ?: throw IllegalStateException("field $PAGE_URL missing in Intent") initWebView() setWebClient() handlePullToRefresh() loadUrl(pageUrl) >private fun handlePullToRefresh() < >@SuppressLint("SetJavaScriptEnabled") private fun initWebView() < webView.settings.javaScriptEnabled = true webView.settings.loadWithOverviewMode = true webView.settings.useWideViewPort = true webView.settings.domStorageEnabled = true webView.webViewClient = object : WebViewClient() < override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) < handler?.proceed() >> > private fun setWebClient() < webView.webChromeClient = object : WebChromeClient() < override fun onProgressChanged( view: WebView, newProgress: Int ) < super.onProgressChanged(view, newProgress) progressBar.progress = newProgress if (newProgress < MAX_PROGRESS && progressBar.visibility == ProgressBar.GONE) < progressBar.visibility = ProgressBar.VISIBLE >if (newProgress == MAX_PROGRESS) < progressBar.visibility = ProgressBar.GONE >> > > override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean < // Check if the key event was the Back button and if there's history if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) < webView.goBack() return true >// If it wasn't the Back key or there's no web page history, exit the activity) return super.onKeyDown(keyCode, event) > private fun loadUrl(pageUrl: String) < webView.loadUrl(pageUrl) >>
Conclusion

All Done. In this android webview example, we learned webview uses, implementation, and manage webpage history, I hope it’s helpful for you, then help me by sharing this post with all your friends

If you have any queries please put your comment below.

Источник

Оцените статью