【问题标题】:onbackpressed not working in kotlin webviewonbackpressed 在 kotlin webview 中不起作用
【发布时间】:2018-12-13 12:31:16
【问题描述】:

我正在处理 web 视图,但当按下返回按钮时应用程序崩溃并且进度条未显示 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)

【问题讨论】:

  • 我相信你应该像你的 logcat 所说的那样显示MainActivity.kt:134 的内容。
  • 是的 if (webview!!.canGoBack()) { ,但无法发布整个代码,因为堆栈溢出不允许它

标签: android webview kotlin onbackpressed


【解决方案1】:

从 onBackPressed() 中移除代码

关于JS提示框,你在真机上测试过吗?

【讨论】:

  • 我删除了 onbackpressed 代码现在后退按钮不起作用
【解决方案2】:

我会高度怀疑您在onBackPressed() 中的本地!!

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

在大多数情况下,调用!! 是个坏主意。以及KotlinNullPointerException 的来源(例如:Kotlin 尝试将 T? 转换为 T,如果为 null,则失败)。

【讨论】:

  • 发布该问题的日志。
猜你喜欢
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多