You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin为WebView加onReceivedError报override不适用于局部函数错误

问题根因

你把onReceivedError错误回调方法的定义写错了位置,当前它是onCreate生命周期方法内的局部函数,不存在可以重写的父类方法,因此会报Modifier 'override' is not applicable to 'local function'错误。同时因为你没有把回调注册到WebViewClient实例中,就算去掉override关键字,WebView加载出错也不会触发你写的处理逻辑。

修复方案

你需要把onReceivedError方法放到WebViewClient的匿名实现类内部,修改后的完整代码如下:

package com.example.myApp

import android.os.Bundle
import android.view.WindowManager
import android.webkit.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    private val BASE_URL = "http://myPage/instruccion/"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        webView.webChromeClient = object : WebChromeClient() {

        }

        // 将错误回调写在WebViewClient的匿名实现内部
        webView.webViewClient = object : WebViewClient() {
            override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
                super.onReceivedError(view, request, error)
                webView.loadUrl("about:blank")
                // 此处需显式指定Context为MainActivity,不能直接用this
                Toast.makeText(this@MainActivity, "Favor de conectarse a la red de EJ", Toast.LENGTH_SHORT).show()
            }
        }

        val settings :WebSettings = webView.settings
        settings.javaScriptEnabled = true
        settings.builtInZoomControls = true
        settings.setSupportZoom(true)
        webView.loadUrl(BASE_URL)
        window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }
}
注意事项
  • Toast.makeText的第一个参数不能直接用this,当前上下文内this指向的是WebViewClient实例,需要显式指定为this@MainActivity拿到Activity的Context
  • 建议重写onReceivedError后保留super.onReceivedError的调用,避免丢失系统默认的错误处理逻辑

内容的提问来源于stack exchange,提问作者Pahoran Alanis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 13:24:03