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

Android Kotlin WebView Fragment的onViewCreated未触发且WebView无法绘制问题求助

Android Kotlin WebView Fragment的onViewCreated未触发且WebView无法绘制问题求助

大家好,我最近在给Android Kotlin应用里的WebView做网络事件追踪,参考了一篇技术文章的方案用Chucker拦截WebView网络请求,但现在遇到了两个核心问题:

  • Fragment的onViewCreated方法完全没触发,控制台看不到我打印的Log.d("MyWebViewFragment", "onViewCreated")日志
  • WebView也没法正常加载目标页面,完全没反应

我已经确认MainActivity里的Fragment事务执行了(能看到Fragment transaction的Log),但Fragment的生命周期似乎卡在了某个环节,实在找不到哪里配置错了。下面是我的代码,麻烦大家帮忙排查一下:

MyWebViewFragment代码

class MyWebViewFragment : Fragment() {

    var isChuckerWebViewEnalbed = BuildConfig.DEBUG

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        Log.d("MyWebViewFragment", "onViewCreated")

        val webView = view.findViewById<WebView>(R.id.webview_container)

        webView.settings.javaScriptEnabled = true

        Log.d("MyWebViewFragment", "Loading URL: https://jmrtno.github.io/Blog_fotografia/")
        webView.loadUrl("https://jmrtno.github.io/Blog_fotografia/")

        // Configuración del WebViewClient para manejar errores
        webView.webViewClient = object : WebViewClient() {
            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                Log.e("MyWebViewFragment", "Error loading URL: ${error?.description}")
            }
        }

        webView?.let {
            webView.layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            webView.settings.javaScriptEnabled = true
            webView.settings.loadWithOverviewMode = true
            webView.settings.useWideViewPort = true
            webView.settings.setSupportZoom(true)
        }

        if (isChuckerWebViewEnalbed) {
            ChuckerWebViewHelper.addJavascriptInterface(webView)
            val builder: OkHttpClient.Builder =
                OkHttpClient.Builder().cookieJar(JavaNetCookieJar(SyncCookieHandler(context)))
            builder.addInterceptor(ChuckerInterceptor(requireContext()))
            ChuckerWebViewHelper
                .enable(true)
                .addWebViewClient(webView)
                .setOkHttpClient(builder.build())
                .addInterceptHost("https://jmrtno.github.io/Blog_fotografia/")
                .interceptAllHosts(false)
                .interceptAllFileExtension(false)
                .handleRequestsWithPayload(true)
                .interceptPreflight(false)
                .setListener(object : ChuckerWebViewHelper.Listener() {
                    override fun onHandleRequestViaOkHttp(request: WebResourceRequest) {
                        Log.d(
                            "onHandleRequestViaOkHttp",
                            "ChuckerWebViewHelper: okHttp handling  ${request.method} ${request.url}"
                        )
                    }

                    override fun onInvalidHostRegex(e: Exception) {
                        Toast.makeText(context, "response KO $e", Toast.LENGTH_LONG).show()
                        Log.d("onInvalidHostRegex", "ChuckerWebViewHelper: $e")
                    }

                    override fun onFailedOKHttpRequest(request: WebResourceRequest, e: Exception) {
                        Log.d(
                            "onFailedOKHttpRequest",
                            "ChuckerWebViewHelper: okHttp handling failed  ${request.method} ${request.url}"
                        )
                    }
                })
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (isChuckerWebViewEnalbed)
            ChuckerWebViewHelper.destroy()
    }
}

Fragment布局XML

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/webview_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyWebViewFragment">

</WebView>

MainActivity代码

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

        if (savedInstanceState == null) {
            Log.d("MainActivity", "Fragment transaction")
            supportFragmentManager.beginTransaction()
                .replace(R.id.fragmentContainer, MyWebViewFragment())
                .commit()
        }
    }
}

MainActivity布局XML

<androidx.constraintlayout.widget.ConstraintLayout 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/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

我已经确认网络权限已经添加,BuildConfig.DEBUG也为true,但就是找不到问题根源,麻烦各位大佬帮忙分析一下,谢谢!

备注:内容来源于stack exchange,提问作者Javi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 06:19:37