【问题标题】:Kotlin webview crashKotlin webview 崩溃
【发布时间】:2017-06-10 10:58:30
【问题描述】:

我正在尝试从 Fragment 访问 WebView,而 kotlin 一直在说:

kotlin.TypeCastException: null cannot be cast to non-null type android.webkit.WebView

我尝试将其设为默认值,然后对其进行初始化,但这也不起作用。关于如何使它工作的任何建议?

我的代码:

private lateinit var webView: WebView

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater!!.inflate(R.layout.editor_edit_fragment, container, false)
    webView = view.findViewById(R.id.webview) as WebView

    resumeWebView()

    return view
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webview" />

</LinearLayout>

【问题讨论】:

  • 看起来view.findViewById(R.id.webview) 正在返回null。您确定在R.layout.editor_edit_fragment 中有一个具有该ID 的视图吗?
  • 我完全确定。刚刚检查过
  • 添加无效?
  • 问题是findViewById 出于某种原因返回null,它就在错误中。您可以将其分配给一个可以为空的变量,但这不会让您有任何收获。
  • @alvarlagerlof 请同时出示您的 editor_edit_fragment.xml。

标签: android android-fragments android-webview kotlin android-view


【解决方案1】:

需要先运行onCreateView,再运行onViewCreated来设置WebView。

class FragmentWebview : Fragment() {

    lateinit var contentView: View


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        contentView = inflater.inflate(R.layout.fragment_fragment_webview, container, false)
        return contentView

    }

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

        val webview = contentView.findViewById<WebView>(R.id.myWebview)

        val url = "http://google.com"


        val webSettings = myWebview.settings

        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true


        webview.webViewClient = WebViewClient()

        webview.loadUrl(url)

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 2022-10-05
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多