onbackpressed无法在Kotlin Webview中工作

时间:2018-12-13 12:31:17

标签: android webview kotlin onbackpressed

我正在使用网络视图,但按后退按钮时应用程序崩溃,并且进度条未显示100% 它打开了一个网站,它也不支持javascript警报框? 这是我的代码

    override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl(url)
            setting!!.domStorageEnabled= true
            setting!!.javaScriptEnabled = true
            return true
        }

    } 
     // Get the web view settings instance
    val settings = webview.settings;
     // Enable java script in web view
    settings.javaScriptEnabled = true

    // 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("https://www.google.com/")

        override fun onBackPressed() {
            if (webview!!.canGoBack()) {
                // If web view have back history, then go to the web view back history
                webview?.goBack()
            }else{
                super.onBackPressed()
            }
        }

Logcat这样说:

E/InputEventSender: Exception dispatching finished signal.
E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI: kotlin.KotlinNullPointerException
        at com.work.social.MainActivity.onBackPressed(MainActivity.kt:134)

2 个答案:

答案 0 :(得分:0)

从onBackPressed()删除代码

关于JS警报框,您是否在真实设备上进行了测试?

答案 1 :(得分:0)

我非常怀疑您在!!中的本地onBackPressed()

override fun onBackPressed() {
    when {
        webview?.canGoBack() == true -> webview.goBack()
        else -> super.onBackPressed()
    }
}

在大多数情况下,致电!!是一个坏主意。还有KotlinNullPointerException的来源(例如:Kotlin尝试将T?强制转换为T,如果为null,则失败)。