androidkotlinwebview

Kotlin WebView - Prevent Opening In New Chrome Browser Window


I have inserted the below code into MainActivity.kt in a blank activity.


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private val url = "http://www.yahoo.com/"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the web view settings instance
        val setting = webview.settings;

        // Enable java script in web view
        setting.javaScriptEnabled = true

        webview.loadUrl(url)

    }
}

I also have inserted a WebView component into activity_main.xml with an id of @+id/webview. When the app loads, the screen redirects to a chrome browser where the Yahoo page is loaded. How do I maintain the browser within the app?

I have tried adding webview.setWebViewRenderProcessClient = webViewClient() before the URL loads, but I get an unresolved reference error when I compile the code.

EDIT

The XML is as follows:

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

</RelativeLayout>

I have also added <uses-permission android:name="android.permission.INTERNET"/> to the AndroidManifest.xml file.


Solution

  • Implement WebView's webClient and set it before calling webView.loadUrl = "#someURL". Example:

    webview.webViewClient = WebViewClient()
    

    For further details regarding WebView check here